一、使用的工具類: HttpClients、HttpClient、CloseableHttpClient【發送請求】;
HttpPut、HttpGet、HttpPost【請求方式:根據接收端指定的請求方法確定】
二、maven 依賴:
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.2</version>
</dependency>
三、請求url: String url = String.format("http://%s:%s/%s",ip,port,method)
四、代碼:根據參數分以下3類:
1、無參數
CloseableHttpClient httpClient = HttpsClient.createDefault();
HttpGet httpGet = new HttpGet(url);//請求方式根據請求的接口確認
//設置超時時間 - time1:連接服務器的時間 、time2:請求的時間、time3:讀取數據的時間
RequestConfig config =
RequestConfig.custom().setConnectTimeout(time1).setConnectionRequestTimeout(time2).setSocketTimeout(time3).build();
httpGet.setConfig(config );
CloseableHttpResponse response = httpClient.excute(httpGet);//發送請求
int statusCode = response.getStatusLine().getStatusCode();//返回狀態碼 : 200-成功。。。
if(statusCode != HttpStatus.SC.OK){ //判斷是否請求成功
System.out.println("請求失敗 ,原因 : " +response.getStatusLine());
throw new Exception("請求失敗! 原因 : " +response.getStatusLine());
}
HttpEntity httpEntity = response.getEntity();//獲取返回的數據
String result = EntityUtils.toString(httpEntity);
//之後將result 轉換成 JSONObject 獲取數據
JSONObject jo = new JSONObject(JSON.parseObject(result));
這個過程會拋出異常,同時需要 關閉資源: EntityUtils.consume(httpEntity)、httpClient.close()、response.close()
2、參數是字符串【暫時分爲2種】
httpGet.addHeader("Content-Type","application/json ; charset= utf-8"); //請求中參數的格式,都需要的
a、放在Header中
在發送請求之前的代碼中,加入以下代碼:
HttpGet.addHeader("key1","value1");
b、放在body中【json】
Map<String,Object> map = new HashMap();//可以作爲參數傳進來
map.put("key",value);
StringEntity entity = new StringEntity(JSON.toJSONString(map))
entity.setContentEncoding("UTF-8");
entity.setContentType("application/json");
httpGet.setEntity(entity);
3、參數是 文件類型【視頻、圖片等】--上傳文件
在發送請求之前加入以下代碼:
HttpEntity httpEntity = new InputStreamEntity(new FileInputStream(new File("D:\\1.txt")));
httpPut.setEntity(httpEntity );
五、使用的時候遇到的錯誤:
1、我遇到的場景是 : 先從一個遠程服務器上下載文件,再存到另外一個遠程服務器上
HttpEntity httpEntity1= new InputStreamEntity(httpEntity.getContent);//httpEntity 是請求第一個服務器下載下來的
在獲取下載的數據的方法結尾關閉了流 【EntityUtils.consume(entity1 )】,導致在執行上面那個代碼時報錯