HTTPClient的方式请求外部接口
POST请求,Map入参
public static String post(String url, Map<String, String> paramsMap) {
CloseableHttpClient client = HttpClients.createDefault();
String responseText = "";
CloseableHttpResponse response = null;
try {
HttpPost method = new HttpPost(url);
if (paramsMap != null) {
List<NameValuePair> paramList = new ArrayList<>();
for (Map.Entry<String, String> param : paramsMap.entrySet()) {
NameValuePair pair = new BasicNameValuePair(param.getKey(), param.getValue());
paramList.add(pair);
}
method.setEntity(new UrlEncodedFormEntity(paramList, ENCODING));
}
response = client.execute(method);
HttpEntity entity = response.getEntity();
if (entity != null) {
responseText = EntityUtils.toString(entity);
}
} catch (Exception e) {
log.error("http post request failed", e);
throw new BusinessException("http post request failed", e);
} finally {
try {
assert response != null;
response.close();
} catch (Exception e) {
log.error("response close failed", e);
}
}
return responseText;
}
POST请求,JsonString 入参
public static String jsonPost(String url, String params) {
CloseableHttpClient client = HttpClients.createDefault();
String responseText = "";
CloseableHttpResponse response = null;
try {
HttpPost method = new HttpPost(url);
method.addHeader("Content-Type", "application/json;charset=UTF-8");
method.setHeader("Accept", "application/json");
StringEntity stringEntity = new StringEntity(params, Charset.forName("UTF-8"));
stringEntity.setContentType("text/json");
method.setEntity(stringEntity);
response = client.execute(method);
HttpEntity entity = response.getEntity();
if (entity != null) {
responseText = EntityUtils.toString(entity);
}
} catch (Exception e) {
log.error("http post request failed", e);
throw new BusinessException("http post request failed", e);
} finally {
try {
assert response != null;
response.close();
} catch (Exception e) {
log.error("response close failed", e);
}
}
return responseText;
}
GET请求方式
public static String get(String url, Map<String, String> paramsMap) {
CloseableHttpClient client = HttpClients.createDefault();
String responseText = "";
CloseableHttpResponse response = null;
try {
StringBuilder getUrl = new StringBuilder(url + "?");
if (paramsMap != null) {
for (Map.Entry<String, String> param : paramsMap.entrySet()) {
getUrl.append(param.getKey()).append("=").append(URLEncoder.encode(param.getValue(), ENCODING)).append("&");
}
}
HttpGet method = new HttpGet(getUrl.toString());
response = client.execute(method);
HttpEntity entity = response.getEntity();
if (entity != null) {
responseText = EntityUtils.toString(entity);
}
} catch (Exception e) {
log.error("http get request failed", e);
throw new BusinessException("http get request failed", e);
} finally {
try {
if (response != null) {
response.close();
}
} catch (Exception e) {
log.error("",e);
}
}
return responseText;
}