一、发送Post请求
在Android中向网络发送Post请求,首先要创建一个HttpURLConnection对象,然后将请求方法设置为"POST"。同时设置一些请求属性,如ContentType,ContentLength等。最后将请求的数据写入发送给服务器。
示例代码:
try { // 创建URL对象 URL url = new URL("http://www.example.com/api"); // 创建HttpURLConnection对象 HttpURLConnection conn = (HttpURLConnection) url.openConnection(); // 设置请求方法为POST conn.setRequestMethod("POST"); // 设置请求属性 conn.setRequestProperty("Content-Type", "application/json"); conn.setRequestProperty("Accept", "application/json"); conn.setRequestProperty("Authorization", "Bearer token"); // 发送请求 OutputStream os = conn.getOutputStream(); os.write(data.getBytes()); os.flush(); os.close(); // 处理服务器响应 BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); String response = ""; String line; while ((line = in.readLine()) != null) { response += line; } in.close(); // 处理响应数据 JSONObject result = new JSONObject(response); } catch (Exception e) { e.printStackTrace(); }
二、发送带参数的Post请求
如果需要发送带参数的Post请求,在将请求数据写入OutputStream之前,需要将参数进行编码并组成查询字符串。常用的编码方式有两种,一种是URL编码,一种是Base64编码。
示例代码:
try { // 创建URL对象 URL url = new URL("http://www.example.com/api"); // 创建HttpURLConnection对象 HttpURLConnection conn = (HttpURLConnection) url.openConnection(); // 设置请求方法为POST conn.setRequestMethod("POST"); // 设置请求属性 conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setRequestProperty("Authorization", "Bearer token"); // 组织请求参数 String data = "name=" + URLEncoder.encode("张三", "UTF-8") + "&age=" + URLEncoder.encode("18", "UTF-8"); // 发送请求 OutputStream os = conn.getOutputStream(); os.write(data.getBytes()); os.flush(); os.close(); // 处理服务器响应 BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); String response = ""; String line; while ((line = in.readLine()) != null) { response += line; } in.close(); // 处理响应数据 JSONObject result = new JSONObject(response); } catch (Exception e) { e.printStackTrace(); }
三、发送Json格式的Post请求
Android中也可以向服务器发送Json格式的Post请求,只需要将请求头设置为"application/json",并将Json数据写入OutputStream中即可。
示例代码:
try { // 创建URL对象 URL url = new URL("http://www.example.com/api"); // 创建HttpURLConnection对象 HttpURLConnection conn = (HttpURLConnection) url.openConnection(); // 设置请求方法为POST conn.setRequestMethod("POST"); // 设置请求属性 conn.setRequestProperty("Content-Type", "application/json"); conn.setRequestProperty("Accept", "application/json"); // 构造请求数据 JSONObject requestData = new JSONObject(); requestData.put("name", "张三"); requestData.put("age", 18); // 发送请求 OutputStream os = conn.getOutputStream(); os.write(requestData.toString().getBytes()); os.flush(); os.close(); // 处理服务器响应 BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); String response = ""; String line; while ((line = in.readLine()) != null) { response += line; } in.close(); // 处理响应数据 JSONObject result = new JSONObject(response); } catch (Exception e) { e.printStackTrace(); }
四、使用OkHttp库发送Post请求
OkHttp是Square公司开源的一款网络库,使用非常方便,可以大大减少网络请求的代码量。
示例代码:
OkHttpClient client = new OkHttpClient.Builder().build(); // 构造请求数据 JSONObject requestData = new JSONObject(); requestData.put("name", "张三"); requestData.put("age", 18); // 构造请求对象 Request request = new Request.Builder() .url("http://www.example.com/api") .post(RequestBody.create(MediaType.parse("application/json"), requestData.toString())) .build(); // 发送请求 try { Response response = client.newCall(request).execute(); String responseString = response.body().string(); JSONObject result = new JSONObject(responseString); } catch (IOException e) { e.printStackTrace(); }
五、处理Post请求返回的文件
在向服务器发送Post请求时,有时需要上传文件,此时需要将文件的二进制内容写入OutputStream中。而在接收服务器返回的文件时,需要将InputStream中读取的二进制内容写入到文件中。
示例代码:
try { // 创建URL对象 URL url = new URL("http://www.example.com/api"); // 创建HttpURLConnection对象 HttpURLConnection conn = (HttpURLConnection) url.openConnection(); // 设置请求方法为POST conn.setRequestMethod("POST"); // 设置请求属性 conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=L7SdJftlSdf0ad9"); // 设置请求体 OutputStream os = conn.getOutputStream(); os.write("--L7SdJftlSdf0ad9\r\n".getBytes()); os.write("Content-Disposition: form-data; name=\"file\"; filename=\"example.txt\"\r\n".getBytes()); os.write("Content-Type: text/plain\r\n\r\n".getBytes()); FileInputStream fis = new FileInputStream(new File("example.txt")); byte[] buffer = new byte[1024]; int len; while ((len = fis.read(buffer)) != -1) { os.write(buffer, 0, len); } fis.close(); os.write("\r\n--L7SdJftlSdf0ad9--\r\n".getBytes()); os.flush(); os.close(); // 处理服务器响应 InputStream is = conn.getInputStream(); FileOutputStream fos = new FileOutputStream(new File("response.txt")); buffer = new byte[1024]; len = 0; while ((len = is.read(buffer)) != -1) { fos.write(buffer, 0, len); } fos.close(); is.close(); } catch (Exception e) { e.printStackTrace(); }