1. 程式人生 > >原生的dopost請求

原生的dopost請求

lex urn ack col request 獲取 malformed on() adl

public static String doPost(String httpUrl, String param) {

        HttpURLConnection connection = null;
        InputStream is = null;
        OutputStream os = null;
        BufferedReader br = null;
        String result = null;
        try {
            URL url = new URL(httpUrl);
            
// 通過遠程url連接對象打開連接 connection = (HttpURLConnection) url.openConnection(); // 設置連接請求方式 connection.setRequestMethod("POST"); // 設置連接主機服務器超時時間:15000毫秒 connection.setConnectTimeout(15000); // 設置讀取主機服務器返回數據超時時間:60000毫秒 connection.setReadTimeout(60000);
// 默認值為:false,當向遠程服務器傳送數據/寫數據時,需要設置為true connection.setDoOutput(true); // 默認值為:true,當前向遠程服務讀取數據時,設置為true,該參數可有可無 connection.setDoInput(true); // 設置傳入參數的格式:請求參數應該是 name1=value1&name2=value2 的形式。 connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
// 設置鑒權信息:Authorization: Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0 connection.setRequestProperty("Authorization", "Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0"); // 通過連接對象獲取一個輸出流 os = connection.getOutputStream(); // 通過輸出流對象將參數寫出去/傳輸出去,它是通過字節數組寫出的 os.write(param.getBytes()); // 通過連接對象獲取一個輸入流,向遠程讀取 if (connection.getResponseCode() == 200) { is = connection.getInputStream(); // 對輸入流對象進行包裝:charset根據工作項目組的要求來設置 br = new BufferedReader(new InputStreamReader(is, "UTF-8")); StringBuffer sbf = new StringBuffer(); String temp = null; // 循環遍歷一行一行讀取數據 while ((temp = br.readLine()) != null) { sbf.append(temp); sbf.append("\r\n"); } result = sbf.toString(); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { // 關閉資源 if (null != br) { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } if (null != os) { try { os.close(); } catch (IOException e) { e.printStackTrace(); } } if (null != is) { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } // 斷開與遠程地址url的連接 connection.disconnect(); } return result; }

原生的dopost請求