目前很多公司项目大多是微服务开发,接口规范一般会采用restful格式,所以请求方式不局限于post和get,还有put和delete。
所以在用httpClient请求的时候,会遇到请求方式的问题,因为非微服务项目只有post和get两种请求方。所以这里做了一个简单的封装。
主要采用
httpPost
和httpPut
的抽象父类HttpEntityEnclosingRequestBase
进行封装。
/**
* 发送 POST 请求(HTTP),K-V形式
*/
public static String doPostByMap(String apiUrl, Map params, String cookie) {
return doXwwwFormUrlencoded(apiUrl,params,cookie,new HttpPost(apiUrl));
}
/**
* 发送 PUT 请求(HTTP),K-V形式
*/
public static String doPutByMap(String apiUrl, Map params, String cookie) {
return doXwwwFormUrlencoded(apiUrl,params,cookie,new HttpPut(apiUrl));
}
/**
*
* 发送 POST 请求(HTTP),json形式
*/
public static String postJson(String url, String params, String cookie) throws IOException {
return doApplicationJson(url, params,cookie,new HttpPost(url));
}
/**
*
* 发送 PUT 请求(HTTP),json形式
*/
public static String putJson(String url, String params, String cookie) throws IOException {
return doApplicationJson(url, params,cookie,new HttpPut(url));
}
参数为 K-V 形式:
public static String doXwwwFormUrlencoded(String apiUrl, Map params, String cookie,HttpEntityEnclosingRequestBase httpRequest){
String httpStr = null;
CloseableHttpResponse response = null;
try {
List pairList = new ArrayList(params.size());
for (Map.Entry entry : params.entrySet()) {
NameValuePair pair = new BasicNameValuePair(entry.getKey(), entry.getValue().toString());
pairList.add(pair);
}
if (StringUtils.isNotEmpty(cookie)) {
httpRequest.setHeader("Cookie", SystemConstant.IYB_LOGIN_COOKIE_KEY + "=" + cookie);
}
httpRequest.setEntity(new UrlEncodedFormEntity(pairList, Charset.forName("UTF-8")));
response = getHttpClient(apiUrl).execute(httpRequest, HttpClientContext.create());
System.out.println(response.toString());
HttpEntity entity = response.getEntity();
httpStr = EntityUtils.toString(entity, "UTF-8");
} catch (IOException e) {
e.printStackTrace();
} finally {
if (response != null) {
try {
EntityUtils.consume(response.getEntity());
} catch (IOException e) {
e.printStackTrace();
}
}
}
return httpStr;
}
参数为 json 形式:
private static String doApplicationJson(String url, String params,String cookie,HttpEntityEnclosingRequestBase httpRequest) {
initConfig(httpRequest);
CloseableHttpResponse response = null;
try {
log.info("url:{}, params: {}", url, params);
HttpEntity httpEntity = new StringEntity(params, ContentType.APPLICATION_JSON);
httpRequest.setEntity(httpEntity);
if (StringUtils.isNotEmpty(cookie)) {
httpRequest.setHeader("Cookie", SystemConstant.IYB_LOGIN_COOKIE_KEY + "=" + cookie);
}
response = getHttpClient(url).execute(httpRequest, HttpClientContext.create());
HttpEntity entity = response.getEntity();
String result = EntityUtils.toString(entity, "utf-8");
EntityUtils.consume(entity);
return result;
} catch (Exception e) {
log.error(e.getMessage());
} finally {
try {
if (response != null)
response.close();
} catch (Exception e) {
log.error(e.getMessage());
}
}
return null;
}