package com.test.http;
import java.io.File;
import java.io.IOException;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
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.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
public class HttpClientUtil {
public Logger logger = Logger.getLogger(HttpClientUtil.class.getName());
private String strURL;
private Map<String, String> httpheadMap;
private Map<String, String> paramsMap;
private String jsonParams;
private String sessionId;
public String sessionIdfromresult;
private String header;
private RequestConfig requestConfig = RequestConfig.custom()
.setSocketTimeout(15000)
.setConnectTimeout(15000)
.setConnectionRequestTimeout(15000)
.build();
public void setURL(String url) {
this.strURL=url;
}
public void setMapParams(Map<String, String> map) {
this.paramsMap=map;
this.jsonParams=new MapJsonChange().mapChangeToJson(map);
}
public void setJsonParams(String jsonParams) {
this.jsonParams=jsonParams;
this.paramsMap=new MapJsonChange().jsonChangeToMap(jsonParams);
}
public void setHttpHead(Map<String, String> map) {
this.httpheadMap=map;
}
public void setHttpHead(String header) {
this.header=header;
}
public void setSessionId(String sessionId) {
this.sessionId=sessionId;
}
//自动获取session
public String getSessionIdFromResult() {
return this.sessionIdfromresult;
}
//设置请求头
public void setHttpHead(HttpGet httpGet) {
if (httpheadMap != null && httpheadMap.size() > 0) {
for (Entry<String, String> e : httpheadMap.entrySet()) {
httpGet.setHeader(e.getKey(), e.getValue());
}
}
if (header != null && header.length() > 0) {
String[] headers=header.split(",");
for(int i=0;i<headers.length;i++) {
httpGet.setHeader(headers[i].substring(0, headers[i].lastIndexOf("=")), headers[i].substring(headers[i].lastIndexOf("=")+1));
}
}
}
//设置请求头
public void setHttpHead(HttpPost httpPost) {
if (httpheadMap != null && httpheadMap.size() > 0) {
for (Entry<String, String> e : httpheadMap.entrySet()) {
httpPost.setHeader(e.getKey(), e.getValue());
}
}
if (header != null && header.length() > 0) {
String[] headers=header.split(",");
for(int i=0;i<headers.length;i++) {
httpPost.setHeader(headers[i].substring(0, headers[i].lastIndexOf("=")), headers[i].substring(headers[i].lastIndexOf("=")+1));
}
}
}
//添加session
public void setSession(HttpGet httpGet) {
if (sessionId != null && sessionId.length() > 0) {
httpGet.setHeader("Cookie", "JSESSIONID=" + sessionId);
}
}
//添加session
public void setSession(HttpPost httpPost) {
if (sessionId != null && sessionId.length() > 0) {
httpPost.setHeader("Cookie", sessionId);
}
}
/**
* 设置参数发送 post请求
*/
public String post() {
logger.info("调取POST接口, URL=["+strURL+"], JSON=["+paramsMap+"]");
HttpPost httpPost = new HttpPost(strURL);// 创建httpPost
if (paramsMap != null && paramsMap.size() > 0) {
StringBuffer sbParams = new StringBuffer();
for (Entry<String, String> e : paramsMap.entrySet()) {
sbParams.append(e.getKey());
sbParams.append("=");
sbParams.append(e.getValue());
sbParams.append("&");
}
try {
//设置参数
StringEntity stringEntity = new StringEntity(sbParams.toString().substring(0,sbParams.length()-1), "UTF-8");
stringEntity.setContentType("application/x-www-form-urlencoded");
httpPost.setEntity(stringEntity);
} catch (Exception e) {
e.printStackTrace();
}
}
return sendHttpPost(httpPost);
}
/**
* 设置参数发送 jsonPost请求
*/
public String jsonPost() {
logger.info("调取JSON接口, URL=["+strURL+"], JSON=["+jsonParams+"]");
HttpPost httpPost = new HttpPost(strURL);// 创建httpPost
if (jsonParams != null && jsonParams.length() > 0) {
try {
//设置参数
StringEntity stringEntity = new StringEntity(jsonParams, "UTF-8");
stringEntity.setContentType("application/json");
httpPost.setEntity(stringEntity);
} catch (Exception e) {
e.printStackTrace();
}
}
return sendHttpPost(httpPost);
}
/**
* 发送Post请求
* @param httpPost
* @return
*/
private String sendHttpPost(HttpPost httpPost) {
String result="";
CloseableHttpClient httpClient = null;
CloseableHttpResponse response = null;
HttpEntity entity = null;
try {
// 创建默认的httpClient实例.
httpClient = HttpClients.createDefault();
httpPost.setConfig(requestConfig);
setHttpHead(httpPost);
setSession(httpPost);
// 执行请求
response = httpClient.execute(httpPost);
entity = response.getEntity();
result = EntityUtils.toString(entity, "UTF-8");
if(response.containsHeader("Set-Cookie"))
this.sessionIdfromresult=response.getFirstHeader("Set-Cookie").toString().replace("Set-Cookie:", "");
//logger.info("getStatusLine结果:"+response.getStatusLine());
if(!response.getStatusLine().toString().contains("200"))
result="ERROR:"+result;
logger.info("请求结果:"+result);
} catch (Exception e) {
result="ERROR:"+e;
logger.error("接口调取失败",e);
e.printStackTrace();
} finally {
try {
// 关闭连接,释放资源
if (response != null) {
response.close();
}
if (httpClient != null) {
httpClient.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
/**
* 发送 get请求
* @param httpUrl
*/
public String get() {
logger.info("调取GET接口, URL=["+strURL+"], JSON=["+jsonParams+"]");
String Params=null;
StringBuffer sbParams = new StringBuffer();
if (paramsMap != null && paramsMap.size() > 0) {
for (Entry<String, String> e : paramsMap.entrySet()) {
sbParams.append(e.getKey());
sbParams.append("=");
sbParams.append(e.getValue());
sbParams.append("&");
}
Params="?"+sbParams.toString().substring(0,sbParams.length()-1);
}
HttpGet httpGet = new HttpGet(strURL+Params);// 创建get请求
return sendHttpGet(httpGet);
}
/**
* 发送Get请求
* @param httpGet
* @return
*/
private String sendHttpGet(HttpGet httpGet) {
String result="";
CloseableHttpClient httpClient = null;
CloseableHttpResponse response = null;
HttpEntity entity = null;
try {
// 创建默认的httpClient实例.
httpClient = HttpClients.createDefault();
httpGet.setConfig(requestConfig);
setHttpHead(httpGet);
setSession(httpGet);
// 执行请求
response = httpClient.execute(httpGet);
entity = response.getEntity();
result = EntityUtils.toString(entity, "UTF-8");
if(response.containsHeader("Set-Cookie"))
this.sessionIdfromresult=response.getFirstHeader("Set-Cookie").toString().replace("Set-Cookie:", "");
if(!response.getStatusLine().toString().contains("200"))
result="ERROR:"+result;
logger.info("请求结果:"+result);
} catch (Exception e) {
result="ERROR:"+e;
logger.error("接口调取失败",e);
e.printStackTrace();
} finally {
try {
// 关闭连接,释放资源
if (response != null) {
response.close();
}
if (httpClient != null) {
httpClient.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
/**
* 上传文件
*/
public String postOfFile() {
HttpPost httppost = new HttpPost(strURL);
if (paramsMap != null && paramsMap.size() > 0) {
StringBuffer sbParams = new StringBuffer();
for (Entry<String, String> e : paramsMap.entrySet()) {
if(!e.getKey().equals("file")) {
sbParams.append(e.getKey());
sbParams.append("=");
sbParams.append(e.getValue());
sbParams.append("&");
}
}
//设置参数
StringEntity stringEntity = new StringEntity(sbParams.toString().substring(0,sbParams.length()-1), "UTF-8");
stringEntity.setContentType("application/x-www-form-urlencoded");
httppost.setEntity(stringEntity);
}
//添加文件
FileBody file = new FileBody(new File(paramsMap.get("file")));
StringBody comment = new StringBody("A binary file of some kind", ContentType.TEXT_PLAIN);
HttpEntity reqEntity = MultipartEntityBuilder.create().addPart("file", file).addPart("comment", comment).build();
httppost.setEntity(reqEntity);
return sendHttpPost(httppost);
}
}
result是请求结果,接口调取成功了会赋值接口返回结果数据,如果失败了赋值失败的具体信息。
其中sessionIdfromresult是从请求结果中获取cookie,有需要做cookie保持的话可以用到这个值,后面会说到。