java HttpClient傳送get和post請求
阿新 • • 發佈:2018-12-17
最近需要用到在A專案裡面發起請求去請求B專案的介面,所以用到了HttpClient,將工具類記錄下,可設定get、post方式,也可以設定session和cookie等header
一、工具類HttpClientUtil
package Utils; import java.io.*; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.Map; public class HttpClientUtils { public static String doGet(String httpUrl) { HttpURLConnection connection = null; InputStream is = null; BufferedReader br = null; String result = null; //返回結果字串 try { //建立遠端url連線物件 URL url = new URL(httpUrl); //通過遠端url連線物件開啟一個連線,強轉成httpURLConnection類 connection = (HttpURLConnection) url.openConnection(); // 設定連線方式:get connection.setRequestMethod("GET"); // 設定連線主機伺服器的超時時間:15000毫秒 connection.setConnectTimeout(15000); // 設定讀取遠端返回的資料時間:60000毫秒 connection.setReadTimeout(60000); // 傳送請求 connection.connect(); // 通過connection連線,獲取輸入流 if (connection.getResponseCode() == 200) { is = connection.getInputStream(); // 封裝輸入流is,並指定字符集 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 != is) { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } //關閉遠端連線 connection.disconnect(); } return result; } public static String doPost(String httpUrl, String param, Map<String, String> headers) { 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); // 設定header請求頭 for (String key : headers.keySet()) { connection.setRequestProperty(key, headers.get(key)); } //通過連線物件獲取一個輸入流,向遠端讀// 通過連線物件獲取一個輸出流 os = connection.getOutputStream(); // 通過輸出流物件將引數寫出去/傳輸出去,它是通過位元組陣列寫出的 //param請求引數應該是 name1=value1&name2=value2 os.write(param.getBytes("utf-8")); 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(); } } connection.disconnect(); } return result; } }
二、main方法呼叫執行
package Utils; import com.google.gson.Gson; import java.util.HashMap; import java.util.Map; public class UtilDemo { public static void main(String[] args) { //get方式 String getResult = HttpClientUtils.doGet("https://www.xxx.com"); //json轉map Map result = new Gson().fromJson(getResult, Map.class); //--------------------------------------------------- //post方式 String webname = "https://www.xxx.com"; //body請求引數 Map<String, Object> body = new HashMap<>(); body.put("key1", "value1"); String sid = "sid111"; String cookie = "cookiexxx"; Map<String, String> headers = new HashMap<>(); headers.put("cookie", cookie); String url = webname + "&sid=" + sid; //map轉json String param = new Gson().toJson(body); String postResult = HttpClientUtils.doPost(url, param, headers); //json轉map Map resutl2 = new Gson().fromJson(postResult, Map.class); } }