一、發送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(); }
原創文章,作者:YFSA,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/133179.html