調用
doPost:map傳參
Map<String,Object> map = new HashMap<>();
map.put("test","test");
String result = HttpClientUtils.getInstance().doPost(url, null, map);
//被調用的方法
@PostMapping("/test")
@ApiOperation("測試")
@ResponseBody
public String test(@RequestBody String requestBody){
return testService.test(requestBody);
}
//取值
String test1= requestBody.split("&")[0].split("=")[1];
String test2= requestBody.split("&")[1].split("=")[1];
doPost:JSON傳參(參數含中文使用JSON傳參否則亂碼)獲得返回值
//JSON傳參獲得返回值
String errmsg = HttpClientUtils.getInstance().doPostWithJson(url,json.toJSONString());
//被調用的方法
@PostMapping("/test")
@ApiOperation("測試")
@ResponseBody
public String test(@RequestBody String template){
return testService.test(template);
}
//取值為JSON格式
JSONObject templateDTO = JSONObject.parseObject(template);
//進行自己的業務操作
return "";
工具類
package com.fxkj.common.util;
import com.alibaba.fastjson.JSONObject;
import com.fxkj.common.exception.BusinessException;
import com.fxkj.common.result.QCodeResult;
import org.apache.http.*;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
/**
* 分裝一個http請求的工具類
*/
public class HttpClientUtils {
private static HttpClientUtils instance;
CloseHttpUtil closeHttpUtil = new CloseHttpUtil();
private HttpClientUtils() {
}
public static synchronized HttpClientUtils getInstance() {
if (instance == null) {
instance = new HttpClientUtils();
}
return instance;
}
/**
* <p>發送GET請求
*
* @param url GET請求地址(帶參數)
* @param headerMap GET請求頭參數容器
* @return 與當前請求對應的響應內容字
*/
public String doGet(String url, Map<String, Object> headerMap) {
String content = null;
CloseableHttpClient httpClient = getHttpClient();
try {
HttpGet getMethod = new HttpGet(url);
//頭部請求信息
if (headerMap != null) {
Iterator iterator = headerMap.entrySet().iterator();
while (iterator.hasNext()) {
Entry entry = (Entry) iterator.next();
getMethod.addHeader(entry.getKey().toString(), entry.getValue().toString());
}
}
//發送get請求
CloseableHttpResponse httpResponse = httpClient.execute(getMethod);
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
try {
//讀取內容
content = EntityUtils.toString(httpResponse.getEntity());
} finally {
httpResponse.close();
}
} else {
throw new BusinessException(httpResponse.getStatusLine().getReasonPhrase());
}
} catch (IOException ex) {
throw new BusinessException(ex.getMessage());
} finally {
try {
closeHttpClient(httpClient);
} catch (Exception e) {
throw new BusinessException(e.getMessage());
}
}
return content;
}
public String doGetRequest(String url, Map<String, String> headMap, Map<String, String> paramMap) {
// 獲取連接客戶端工具
CloseableHttpClient httpClient = HttpClients.createDefault();
String entityStr = null;
CloseableHttpResponse response = null;
try {
/*
* 由於GET請求的參數都是拼裝在URL地址后方,所以我們要構建一個URL,帶參數
*/
URIBuilder uriBuilder = new URIBuilder(url);
for (Entry<String, String> param : paramMap.entrySet()) {
uriBuilder.addParameter(param.getKey(), param.getValue());
}
// 根據帶參數的URI對象構建GET請求對象
HttpGet httpGet = new HttpGet(uriBuilder.build());
/*
* 添加請求頭信息
*/
if (null != headMap) {
for (Entry<String, String> header : headMap.entrySet()) {
httpGet.addHeader(header.getKey(), header.getValue());
}
}
/*httpGet.addHeader("Content-Type", "application/VIID+JSON;charset=utf8");
httpGet.addHeader("User-Identify","12345678905030000000");*/
closeHttpUtil.setTimeOut(httpGet);
// 執行請求
response = httpClient.execute(httpGet);
// 獲得響應的實體對象
HttpEntity entity = response.getEntity();
// 使用Apache提供的工具類進行轉換成字符串
entityStr = EntityUtils.toString(entity, "UTF-8");
} catch (ClientProtocolException e) {
System.err.println("Http協議出現問題");
e.printStackTrace();
} catch (ParseException e) {
System.err.println("解析錯誤");
e.printStackTrace();
} catch (URISyntaxException e) {
System.err.println("URI解析異常");
e.printStackTrace();
} catch (IOException e) {
System.err.println("IO異常");
e.printStackTrace();
} finally {
// 釋放連接
closeHttpUtil.close(response, httpClient);
}
return entityStr;
}
/**
* <p>發送POST請求
*
* @param url POST請求地址
* @param headerMap POST請求頭參數容器
* @param parameterMap POST請求參數容器
* @return 與當前請求對應的響應內容字
*/
public String doPost(String url, Map<String, Object> headerMap, Map<String, Object> parameterMap) {
String content = null;
CloseableHttpClient httpClient = getHttpClient();
try {
HttpPost postMethod = new HttpPost(url);
postMethod.setHeader("Content-Type", "application/json;charset=utf-8");
postMethod.setHeader("Accept", "application/json;charset=utf-8");
//頭部請求信息
if (headerMap != null) {
Iterator iterator = headerMap.entrySet().iterator();
while (iterator.hasNext()) {
Entry entry = (Entry) iterator.next();
postMethod.addHeader(entry.getKey().toString(), entry.getValue().toString());
}
}
if (parameterMap != null) {
Iterator iterator = parameterMap.keySet().iterator();
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
while (iterator.hasNext()) {
String key = (String) iterator.next();
nvps.add(new BasicNameValuePair(key, String.valueOf(parameterMap.get(key))));
}
postMethod.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
}
CloseableHttpResponse httpResponse = httpClient.execute(postMethod);
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
try {
//讀取內容
content = EntityUtils.toString(httpResponse.getEntity());
} finally {
httpResponse.close();
}
} else {
throw new BusinessException(httpResponse.getStatusLine().getReasonPhrase());
}
} catch (IOException ex) {
throw new BusinessException(ex.getMessage());
} finally {
try {
closeHttpClient(httpClient);
} catch (Exception e) {
throw new BusinessException(e.getMessage());
}
}
return content;
}
public static String doPostWithJson(String url, String json) {
String returnValue = JsonUtils.write(QCodeResult.fail("接口異常!"));
CloseableHttpClient httpClient = HttpClients.createDefault();
ResponseHandler<String> responseHandler = new BasicResponseHandler();
try {
//第一步:創建HttpClient對象
httpClient = HttpClients.createDefault();
//第二步:創建httpPost對象
HttpPost httpPost = new HttpPost(url);
RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(30000)
.setSocketTimeout(30000).setConnectTimeout(10000).build();
//第三步:給httpPost設置JSON格式的參數
StringEntity requestEntity = new StringEntity(json, "utf-8");
requestEntity.setContentEncoding("UTF-8");
httpPost.setHeader("Content-type", "application/json");
httpPost.setEntity(requestEntity);
httpPost.setConfig(requestConfig);
//第四步:發送HttpPost請求,獲取返回值
returnValue = httpClient.execute(httpPost, responseHandler); //調接口獲取返回值時,必須用此方法
// System.out.println("請求返回:" + returnValue);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
httpClient.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//第五步:處理返回值
return returnValue;
}
public CloseableHttpClient getHttpClient() {
return HttpClients.createDefault();
}
private void closeHttpClient(CloseableHttpClient client) throws IOException {
if (client != null) {
client.close();
}
}
public static void get(String url) {
HttpGet request = new HttpGet(url);
try {
HttpResponse response = HttpClients.createDefault().execute(request);
if (response.getStatusLine().getStatusCode() == 200) {
EntityUtils.toString(response.getEntity());
}
} catch (Exception e) {
}
}
}