package cn.qtt.commons.utils;
import java.io.File;
import java.io.InputStream;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import net.sf.json.JSONObject;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
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.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* HTTP接口请求工具
*/
public class HttpUtils {
private final static Logger logger = LoggerFactory
.getLogger(HttpUtils.class);
public final static String GBK = "GBK";
public final static String GB2312 = "GB2312";
public final static String UTF8 = "UTF-8";
private final static int TIME_OUT = 30 * 1000; // 缺省超时时间
/**
* GET方式调用接口,编码缺省使用UTF-8
*
* @param url
* 接口url
* @param params
* 参数,可为null
* @param headers
* 头信息,可为null
* @param charset
* 编码,缺省使用UTF-8
* @return 请求结果
* @throws Exception
* 请求异常,网络连接失败等
*/
public static HttpResult get(String url) throws Exception {
return get(url, null, null, null);
}
/**
* GET方式调用接口
*
* @param url
* 接口url
* @param params
* 参数,可为null
* @param headers
* 头信息,可为null
* @param charset
* 编码,缺省使用UTF-8
* @return 请求结果
* @throws Exception
* 请求异常,网络连接失败等
*/
public static HttpResult get(String url, Map<String, String> params,
Map<String, String> headers, String charset) throws Exception {
final String xFunctionName = "get()";
logger.info(xFunctionName + ".begin");
HttpResult ret = new HttpResult();
HttpClient client = null;
try {
logger.info("接口url:" + url);
if (StringUtils.isBlank(charset)) {
charset = UTF8;
}
// 添加参数
if (null != params) {
StringBuffer sb = new StringBuffer();
for (Iterator<Map.Entry<String, String>> iterator = params
.entrySet().iterator(); iterator.hasNext();) {
Map.Entry<String, String> entry = iterator.next();
sb.append("&")
.append(entry.getKey())
.append("=")
.append(URLEncoder.encode(entry.getValue(), charset));
}
if (url.indexOf("?") < 0) {
sb = sb.replace(0, 1, "?");
}
logger.info("接口参数:" + sb.toString());
url += sb.toString();
}
client = new HttpClient();
setTimeout(client);
GetMethod method = new GetMethod(url);
// method.setRequestHeader("Content-Type", "*; charset=UTF-8");
// 添加header
if (null != headers) {
for (Iterator<Map.Entry<String, String>> iterator = headers
.entrySet().iterator(); iterator.hasNext();) {
Map.Entry<String, String> entry = iterator.next();
method.addRequestHeader(entry.getKey(), entry.getValue());
}
}
int code = client.executeMethod(method);
ret.setCode(code);
ret.setResult(method.getResponseBodyAsString());
ret.setDatas(method.getResponseBody());
logger.info("接口返回状态:" + code);
logger.info("接口返回值:" + ret.getResult());
return ret;
} catch (Exception e) {
logger.error(xFunctionName, e);
throw e;
} finally {
client = null;
logger.info(xFunctionName + ".end");
}
}
/**
* POST方式调用接口,编码,缺省使用UTF-8
*
* @param url
* 接口url
* @return 请求结果
* @throws Exception
* 请求异常,网络连接失败等
*/
public static HttpResult post(String url) throws Exception {
return post(url, null, null, null);
}
/**
* POST方式调用接口
*
* @param url
* 接口url
* @param params
* 参数,可为null
* @param headers
* 头信息,可为null
* @param charset
* 编码,缺省使用UTF-8
* @return 请求结果
* @throws Exception
* 请求异常,网络连接失败等
*/
public static HttpResult post(String url, Map<String, String> params,
Map<String, String> headers, String charset) throws Exception {
final String xFunctionName = "post()";
logger.info(xFunctionName + ".begin");
HttpResult ret = new HttpResult();
HttpClient client = null;
DurationUtils durationUtils = new DurationUtils();
durationUtils.start();
try {
logger.info("接口url:" + url);
if (StringUtils.isBlank(charset)) {
charset = UTF8;
}
client = new HttpClient();
setTimeout(client);
PostMethod method = new PostMethod(url);
method.getParams().setContentCharset(charset);
// method.setRequestHeader("Content-Type", "*; charset=UTF-8");
// 添加header
if (null != headers) {
for (Iterator<Map.Entry<String, String>> iterator = headers
.entrySet().iterator(); iterator.hasNext();) {
Map.Entry<String, String> entry = iterator.next();
method.addRequestHeader(entry.getKey(), entry.getValue());
}
}
// 添加参数
if (null != params) {
for (Iterator<Map.Entry<String, String>> iterator = params
.entrySet().iterator(); iterator.hasNext();) {
Map.Entry<String, String> entry = iterator.next();
method.setParameter(entry.getKey(), entry.getValue());
}
}
int code = client.executeMethod(method);
// 打印响应header
Header[] hs = method.getResponseHeaders();
StringBuffer rspHeaders = new StringBuffer("接口ResonseHeader:");
for (Header header : hs) {
rspHeaders.append(header.getName() + ":" + header.getValue())
.append("\n");
}
logger.debug(rspHeaders.toString());
ret.setCode(code);
ret.setResult(method.getResponseBodyAsString());
ret.setDatas(method.getResponseBody());
ret.setDuration(durationUtils.stop());
logger.info("接口返回状态:" + code);
logger.info("接口返回值:" + ret.getResult());
return ret;
} catch (Exception e) {
logger.error(xFunctionName, e);
throw e;
} finally {
client = null;
logger.info(xFunctionName + ".end");
}
}
/**
* POST方式调用接口
*
* @param url
* 接口url
* @param entity
* 请求消息,不可为null
* @param headers
* 头信息,可为null
* @param charset
* 编码,缺省使用UTF-8
* @return 请求结果
* @throws Exception
* 请求异常,网络连接失败等
*/
public static HttpResult postEntity(String url, RequestEntity entity,
Map<String, String> headers, String charset) throws Exception {
final String xFunctionName = "postEntity()";
logger.info(xFunctionName + ".begin");
HttpResult ret = new HttpResult();
HttpClient client = null;
DurationUtils durationUtils = new DurationUtils();
durationUtils.start();
try {
logger.info("接口url:" + url);
if (StringUtils.isBlank(charset)) {
charset = UTF8;
}
client = new HttpClient();
setTimeout(client);
PostMethod method = new PostMethod(url);
method.getParams().setContentCharset(charset);
// method.setRequestHeader("Content-Type", "*; charset=UTF-8");
// 添加header
if (null != headers) {
for (Iterator<Map.Entry<String, String>> iterator = headers
.entrySet().iterator(); iterator.hasNext();) {
Map.Entry<String, String> entry = iterator.next();
method.addRequestHeader(entry.getKey(), entry.getValue());
}
}
// 添加参数
method.setRequestEntity(entity);
int code = client.executeMethod(method);
// 打印响应header
Header[] hs = method.getResponseHeaders();
StringBuffer rspHeaders = new StringBuffer("接口ResonseHeader:");
for (Header header : hs) {
rspHeaders.append(header.getName() + ":" + header.getValue())
.append("\n");
}
logger.debug(rspHeaders.toString());
ret.setCode(code);
ret.setResult(method.getResponseBodyAsString());
ret.setDatas(method.getResponseBody());
ret.setDuration(durationUtils.stop());
logger.info("接口返回状态:" + code);
logger.info("接口返回值:" + ret.getResult());
return ret;
} catch (Exception e) {
logger.error(xFunctionName, e);
throw e;
} finally {
client = null;
logger.info(xFunctionName + ".end");
}
}
/**
* POST方式调用接口
*
* @param url
* 接口url
* @param body
* 参数,可为null
* @param headers
* 头信息,可为null
* @param charset
* 编码,缺省使用UTF-8
* @return 请求结果
* @throws Exception
* 请求异常,网络连接失败等
*/
@SuppressWarnings("deprecation")
public static HttpResult postBody(String url, String body,
Map<String, String> headers, String charset) throws Exception {
final String xFunctionName = "postBody()";
logger.info(xFunctionName + ".begin");
HttpResult ret = new HttpResult();
HttpClient client = null;
DurationUtils durationUtils = new DurationUtils();
durationUtils.start();
try {
logger.info("接口url:" + url);
if (StringUtils.isBlank(charset)) {
charset = UTF8;
}
client = new HttpClient();
setTimeout(client);
PostMethod method = new PostMethod(url);
method.getParams().setContentCharset(charset);
// method.setRequestHeader("Content-Type", "*; charset=UTF-8");
// 添加header
if (null != headers) {
for (Iterator<Map.Entry<String, String>> iterator = headers
.entrySet().iterator(); iterator.hasNext();) {
Map.Entry<String, String> entry = iterator.next();
method.addRequestHeader(entry.getKey(), entry.getValue());
}
}
// 添加参数
method.setRequestBody(body);
int code = client.executeMethod(method);
ret.setCode(code);
ret.setResult(method.getResponseBodyAsString());
ret.setDatas(method.getResponseBody());
ret.setDuration(durationUtils.stop());
logger.info("接口返回状态:" + code);
logger.info("接口返回值:" + ret.getResult());
return ret;
} catch (Exception e) {
logger.error(xFunctionName, e);
throw e;
} finally {
client = null;
logger.info(xFunctionName + ".end");
}
}
/**
* http请求资源文件
* @param url
* @param fileMap 资源文件
* @param contextMap 内容 可为null
* @return
* @throws Exception
*/
@SuppressWarnings({ "deprecation", "unchecked" })
public static HttpResult postFile(String url,
Map<String, String> fileMap, Map<String, String> contextMap) throws Exception {
final String xFunctionName = "postFile()";
logger.info(xFunctionName + ".begin");
DurationUtils durationUtils = new DurationUtils();
durationUtils.start();
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
HttpPost httppost = new HttpPost(url);
HttpResult ret = new HttpResult();
Charset charSet = Charset.forName("UTF-8");
MultipartEntityBuilder aa = MultipartEntityBuilder.create();
Iterator<Entry<String, String>> itFile = fileMap.entrySet()
.iterator();
FileBody fileBody = null;
while (itFile.hasNext()) {
Entry<String, String> entry = itFile.next();
fileBody = new FileBody(new File(entry.getValue()));
aa.addPart(entry.getKey(), fileBody);
}
if(contextMap!=null){
Iterator<Entry<String, String>> itContext = contextMap.entrySet()
.iterator();
StringBody context = null;
while (itContext.hasNext()) {
Entry<String, String> entry = itContext.next();
context = new StringBody(entry.getValue().toString(), charSet);
aa.addPart(entry.getKey(), context);
}
}
HttpEntity reqEntity = aa.build();
httppost.setEntity(reqEntity);
HttpResponse response = httpclient.execute(httppost);
int statusCode = response.getStatusLine().getStatusCode();
HttpEntity resEntity = response.getEntity();
String str = EntityUtils.toString(resEntity);
Map<String, String> map = JSONObject.fromObject(str); // httpclient自带的工具类读取返回数据
ret.setCode(statusCode);
ret.setResult(str);
ret.setDuration(durationUtils.stop());
logger.info("接口返回状态:" + statusCode);
logger.info("接口返回值:" + map);
return ret;
} catch (Exception e) {
logger.error(xFunctionName, e);
throw e;
} finally {
httpclient = null;
logger.info(xFunctionName + ".end");
}
}
/**
* 设置请求超时时间
*/
private static void setTimeout(HttpClient client) {
client.getHttpConnectionManager().getParams()
.setConnectionTimeout(TIME_OUT);
client.getHttpConnectionManager().getParams().setSoTimeout(TIME_OUT);
}
public static class HttpResult {
private int code;
private String result;
private InputStream inputStream;
private byte[] datas;
private int duration;
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getResult() {
return result;
}
public void setResult(String result) {
this.result = result;
}
public InputStream getInputStream() {
return inputStream;
}
public void setInputStream(InputStream inputStream) {
this.inputStream = inputStream;
}
public byte[] getDatas() {
return datas;
}
public void setDatas(byte[] datas) {
this.datas = datas;
}
public int getDuration() {
return duration;
}
public void setDuration(int duration) {
this.duration = duration;
}
}
public static void main(String[] args) throws Exception {
// JSONObject jsonObject = new JSONObject();
// jsonObject.put("productId", "03470114293038235");
// postBody("http://127.0.0.1:8080/DmscInterface/weixin/order.do",
// jsonObject.toString(), null, null);
// Map<String, String> headers = new HashMap<String, String>();
// headers.put("apikey", "61887296d24be68e565cbc964a6c89fe");
// 生成短链接
// String shortUrl = new
// ShortUrlServiceBaiduImpl().shorten("http://api.map.baidu.com/marker?location=39.916979519873,116.41004950566&title=会议地点&content=百度奎科大厦&output=html");
// System.out.println("short:" + shortUrl);
}
}
httpUtils工具类
最新推荐文章于 2024-08-15 18:37:29 发布