HttpClient例子
2016-05-09 10:28
363 查看
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
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.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* HTTP 请求客户端(目前支持POS请求)
* @author Administrator
*
*/
public class HttpClientUtil {
private static Logger logger = LoggerFactory.getLogger(HttpClientUtil.class);
private final static String UTF8 = "UTF-8";
private final static String RTN_CODE = "code";
private final static String RTN_MSG = "msg";
private final static String RTN_RSLT = "data";
private final static int TIMEOUT = 20000;
/**
* 发送请求
*
* @param url
* Request Url
* @param headers
* Request Headers
* @param reqParam
* Request Params
* @param charSet
* 字符集,默认UTF-8
* @param timeout
* 超时时间
* @return
*/
@SuppressWarnings("rawtypes")
public static Map postSend(String url, Map<String, String> headers,
Object reqParam, String charSet, int timeout) {
HttpPost httpPost = getHttpPost(url, headers, reqParam, charSet, timeout);
return sendPost(httpPost);
}
/**
*
* @param url
* Request Url
* @param headers
* Request Headers
* @param reqParam
* Request Params
* @return
*/
@SuppressWarnings("rawtypes")
public static Map postSend(String url, Map<String, String> headers,
Object reqParam) {
return postSend(url, headers, reqParam, UTF8, TIMEOUT);
}
/**
* 发送请求
*
* @param httpPost
* @return
*/
@SuppressWarnings({"rawtypes", "unchecked"})
private static Map sendPost(HttpPost httpPost) {
// 创建默认的httpClient实例
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse httpResponse = null;
Map<String, Object> rtnMap = null;
String str = "ERROR-REQ";
try {
httpResponse = httpClient.execute(httpPost);
// 请求发送成功,并得到响应
int statusCode = httpResponse.getStatusLine()
.getStatusCode();
if (statusCode == HttpStatus.SC_OK) {
str = EntityUtils.toString(httpResponse.getEntity());
rtnMap = getRtnMap("200000","Success",str);
}else{
rtnMap = getRtnMap("200001","请求失败!", statusCode);
}
} catch (ClientProtocolException e1) {
// e1.printStackTrace();
logger.error("HttpClient Request ClientProtocolException!"
+ e1.getMessage(), e1);
rtnMap = getRtnMap("200444","Send Exception","Send ProtocolException"+e1.getMessage());
} catch (IOException e2) {
e2.printStackTrace();
logger.error("HttpClient Request IOException!" + e2.getMessage(),
e2);
rtnMap = getRtnMap("200444","Send Exception","Send IOException"+e2.getMessage());
} finally {
try {
if (httpClient != null) {
httpClient.close();
}
if (httpResponse != null) {
httpResponse.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return rtnMap;
}
/**
* 设置请求参数List<NameValuePair> nvps
*
* @param url
* Request Url
* @param headers
* Request Headers
* @param reqParam
* Request Params
* @param charSet
* 字符集,默认UTF-8
* @param timeout
* 超时时间
*/
@SuppressWarnings("unchecked")
private static HttpPost getHttpPost(String url, Map<String, String> headers,
Object obj, String charset, int timeout) {
HttpPost httpost = new HttpPost(url);
try {
// 请求参数
if (obj != null) {
HttpEntity httpEntity = null;
if (obj instanceof Map) {
List<NameValuePair> nameValues = new ArrayList<NameValuePair>();
Map<String, String[]> params = (Map<String, String[]>) obj;
for (Map.Entry<String, String[]> entry : params
.entrySet()) {
for (String value : entry.getValue()) {
nameValues.add(new BasicNameValuePair(
entry.getKey(), value));
}
}
httpEntity = new UrlEncodedFormEntity(nameValues, charset);
} else if (obj instanceof String) {
String xmlStr = (String) obj;
httpEntity = new StringEntity(xmlStr, charset);
}
httpost.setEntity(httpEntity);
}
// 请求头信息(待写)
if (headers != null) {
for (Map.Entry<String, String> entry : headers.entrySet()) {
httpost.addHeader(entry.getKey(), entry.getValue());
}
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
httpost.setConfig(setHttpTimeOut(timeout));
return httpost;
}
/**
* 设置默认请求和传输超时时间
*
* @param timeout
默认20000
* @return
*/
private static RequestConfig setHttpTimeOut(int timeout) {
RequestConfig defaultRequestConfig = RequestConfig.custom()
.setSocketTimeout(timeout).setConnectTimeout(timeout)
.setConnectionRequestTimeout(timeout)
.setStaleConnectionCheckEnabled(true).build();
return defaultRequestConfig;
}
/**
* 获取返回的Map
* @param rtnCode
* @param rtnMsg
* @return
*/
@SuppressWarnings("rawtypes")
private static Map getRtnMap(String rtnCode, String rtnMsg, Object rslt){
Map<String, Object> rtnMap = new HashMap<>();
rtnMap.put(RTN_CODE, rtnCode);
rtnMap.put(RTN_MSG, rtnMsg);
rtnMap.put(RTN_RSLT, rslt);
return rtnMap;
}
}
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
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.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* HTTP 请求客户端(目前支持POS请求)
* @author Administrator
*
*/
public class HttpClientUtil {
private static Logger logger = LoggerFactory.getLogger(HttpClientUtil.class);
private final static String UTF8 = "UTF-8";
private final static String RTN_CODE = "code";
private final static String RTN_MSG = "msg";
private final static String RTN_RSLT = "data";
private final static int TIMEOUT = 20000;
/**
* 发送请求
*
* @param url
* Request Url
* @param headers
* Request Headers
* @param reqParam
* Request Params
* @param charSet
* 字符集,默认UTF-8
* @param timeout
* 超时时间
* @return
*/
@SuppressWarnings("rawtypes")
public static Map postSend(String url, Map<String, String> headers,
Object reqParam, String charSet, int timeout) {
HttpPost httpPost = getHttpPost(url, headers, reqParam, charSet, timeout);
return sendPost(httpPost);
}
/**
*
* @param url
* Request Url
* @param headers
* Request Headers
* @param reqParam
* Request Params
* @return
*/
@SuppressWarnings("rawtypes")
public static Map postSend(String url, Map<String, String> headers,
Object reqParam) {
return postSend(url, headers, reqParam, UTF8, TIMEOUT);
}
/**
* 发送请求
*
* @param httpPost
* @return
*/
@SuppressWarnings({"rawtypes", "unchecked"})
private static Map sendPost(HttpPost httpPost) {
// 创建默认的httpClient实例
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse httpResponse = null;
Map<String, Object> rtnMap = null;
String str = "ERROR-REQ";
try {
httpResponse = httpClient.execute(httpPost);
// 请求发送成功,并得到响应
int statusCode = httpResponse.getStatusLine()
.getStatusCode();
if (statusCode == HttpStatus.SC_OK) {
str = EntityUtils.toString(httpResponse.getEntity());
rtnMap = getRtnMap("200000","Success",str);
}else{
rtnMap = getRtnMap("200001","请求失败!", statusCode);
}
} catch (ClientProtocolException e1) {
// e1.printStackTrace();
logger.error("HttpClient Request ClientProtocolException!"
+ e1.getMessage(), e1);
rtnMap = getRtnMap("200444","Send Exception","Send ProtocolException"+e1.getMessage());
} catch (IOException e2) {
e2.printStackTrace();
logger.error("HttpClient Request IOException!" + e2.getMessage(),
e2);
rtnMap = getRtnMap("200444","Send Exception","Send IOException"+e2.getMessage());
} finally {
try {
if (httpClient != null) {
httpClient.close();
}
if (httpResponse != null) {
httpResponse.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return rtnMap;
}
/**
* 设置请求参数List<NameValuePair> nvps
*
* @param url
* Request Url
* @param headers
* Request Headers
* @param reqParam
* Request Params
* @param charSet
* 字符集,默认UTF-8
* @param timeout
* 超时时间
*/
@SuppressWarnings("unchecked")
private static HttpPost getHttpPost(String url, Map<String, String> headers,
Object obj, String charset, int timeout) {
HttpPost httpost = new HttpPost(url);
try {
// 请求参数
if (obj != null) {
HttpEntity httpEntity = null;
if (obj instanceof Map) {
List<NameValuePair> nameValues = new ArrayList<NameValuePair>();
Map<String, String[]> params = (Map<String, String[]>) obj;
for (Map.Entry<String, String[]> entry : params
.entrySet()) {
for (String value : entry.getValue()) {
nameValues.add(new BasicNameValuePair(
entry.getKey(), value));
}
}
httpEntity = new UrlEncodedFormEntity(nameValues, charset);
} else if (obj instanceof String) {
String xmlStr = (String) obj;
httpEntity = new StringEntity(xmlStr, charset);
}
httpost.setEntity(httpEntity);
}
// 请求头信息(待写)
if (headers != null) {
for (Map.Entry<String, String> entry : headers.entrySet()) {
httpost.addHeader(entry.getKey(), entry.getValue());
}
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
httpost.setConfig(setHttpTimeOut(timeout));
return httpost;
}
/**
* 设置默认请求和传输超时时间
*
* @param timeout
默认20000
* @return
*/
private static RequestConfig setHttpTimeOut(int timeout) {
RequestConfig defaultRequestConfig = RequestConfig.custom()
.setSocketTimeout(timeout).setConnectTimeout(timeout)
.setConnectionRequestTimeout(timeout)
.setStaleConnectionCheckEnabled(true).build();
return defaultRequestConfig;
}
/**
* 获取返回的Map
* @param rtnCode
* @param rtnMsg
* @return
*/
@SuppressWarnings("rawtypes")
private static Map getRtnMap(String rtnCode, String rtnMsg, Object rslt){
Map<String, Object> rtnMap = new HashMap<>();
rtnMap.put(RTN_CODE, rtnCode);
rtnMap.put(RTN_MSG, rtnMsg);
rtnMap.put(RTN_RSLT, rslt);
return rtnMap;
}
}
相关文章推荐
- 程序模拟HTTP请求
- Spring HTTP Invoker使用介绍
- TCP/IP详解学习笔记(5)-IP选路,动态选路,和一些细节
- linux tcpdump
- NAT网络下TCP连接建立时可能SYN包被服务器忽略-tcp_tw_recycle
- TCP/IP详解学习笔记(4)-ICMP协议,ping和Traceroute
- 【网络编程/C++】修改本机ip地址
- 中间人攻击实验 https
- TCP/IP详解学习笔记(3)-IP协议,ARP协议,RARP协议
- ios网络学习-- UIWebView的加载本地数据的三种方式
- linux-tcpdump抓包-邮件加密配置-nmap扫描-tcpwrap的使用
- 当约架成为一门生意 游戏还可以这样创新
- 如何防止运营商网络劫持,避免被他人强行插入广告?
- TCP/IP详解学习笔记(2)-数据链路层
- TCP实现多个客户端与服务端 数据 传输
- TCP/IP详解学习笔记(1)-基本概念
- Nodejs获取网络数据并生成Excel表格
- Retrofit+OKHttp 教你怎么持久化管理Cookie
- WPA-PSK无线网络破解原理及过程(转)
- chrome浏览器自带的开发者工具查看http头