廢話不多少說,直接上代碼
//get請求 public static void HttpClientGet(String url) throws Exception { // 獲取http客戶端 CloseableHttpClient client = HttpClients.createDefault(); // 通過httpget方式來實現我們的get請求 HttpGet httpGet = new HttpGet(url); // 通過client調用execute方法,得到我們的執行結果就是一個response,所有的數據都封裝在response里面了 CloseableHttpResponse Response = client.execute(httpGet); // 所有的響應的數據,也全部都是封裝在HttpEntity里面 HttpEntity entity = Response.getEntity(); // 通過EntityUtils 來將我們的數據轉換成字符串 String str = EntityUtils.toString(entity, "UTF-8"); // EntityUtils.toString(entity) System.out.println(str); // 關閉 Response.close(); } //post請求 public static void HttpClientPost(String url, String... args) throws Exception { // 獲取默認的請求客戶端 CloseableHttpClient client = HttpClients.createDefault(); // 通過HttpPost來發送post請求 HttpPost httpPost = new HttpPost(url); /* * post帶參數開始 */ // 第三步:構造list集合,往里面丟數據 List<NameValuePair> list = new ArrayList<>(); BasicNameValuePair basicNameValuePair = new BasicNameValuePair("command", args[0]); list.add(basicNameValuePair); // 第二步:我們發現Entity是一個接口,所以只能找實現類,發現實現類又需要一個集合,集合的泛型是NameValuePair類型 UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(list); // 第一步:通過setEntity 將我們的entity對象傳遞過去 httpPost.setEntity(formEntity); /* * post帶參數結束 */ // HttpEntity // 是一個中間的橋梁,在httpClient里面,是連接我們的請求與響應的一個中間橋梁,所有的請求參數都是通過HttpEntity攜帶過去的 // 通過client來執行請求,獲取一個響應結果 CloseableHttpResponse response = client.execute(httpPost); HttpEntity entity = response.getEntity(); String str = EntityUtils.toString(entity, "UTF-8"); System.out.println(str); // 關閉 response.close(); }