一、maven引入apache
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>4.4.4</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.5</version>
</dependency>
二、封裝post請求方法
public static String httpPost(String url,Map map){
// 返回body
String body = null;
// 獲取鏈接客戶端工具
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse httpResponse=null;
// 二、建立一個HttpPost請求
HttpPost post = new HttpPost(url);
// 五、設置header信息
/**header中通用屬性*/
post.setHeader("Accept","*/*");
post.setHeader("Accept-Encoding","gzip, deflate");
post.setHeader("Cache-Control","no-cache");
post.setHeader("Connection", "keep-alive");
post.setHeader("Content-Type", "application/json;charset=UTF-8");
/**業務參數*/
post.setHeader("test1","test1");
post.setHeader("test2",2);
// 設置參數
if (map != null) {
//System.out.println(JSON.toJSONString(map));
try {
StringEntity entity1=new StringEntity(JSON.toJSONString(map),"UTF-8");
entity1.setContentEncoding("UTF-8");
entity1.setContentType("application/json");
post.setEntity(entity1);
// 七、執行post請求操做,並拿到結果
httpResponse = httpClient.execute(post);
// 獲取結果實體
HttpEntity entity = httpResponse.getEntity();
if (entity != null) {
// 按指定編碼轉換結果實體爲String類型
body = EntityUtils.toString(entity, "UTF-8");
}
try {
httpResponse.close();
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
}
return body;
}
三、封裝GET請求方法
public static String httpGet(String url){
// 獲取鏈接客戶端工具
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse httpResponse=null;
String finalString = null;
HttpGet httpGet = new HttpGet(url);
/**公共參數添加至httpGet*/
/**header中通用屬性*/
httpGet.setHeader("Accept","*/*");
httpGet.setHeader("Accept-Encoding","gzip, deflate");
httpGet.setHeader("Cache-Control","no-cache");
httpGet.setHeader("Connection", "keep-alive");
httpGet.setHeader("Content-Type", "application/json;charset=UTF-8");
/**業務參數*/