HttpClent请求


package com.util.pay;


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.dom4j.DocumentException;
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());
				// 测试增加
				// JSONObject jsonObject = JSONObject.parseObject(str);
				// str = jsonObject.getString("data");
				// *********测试END
				String data = BankXmlUtils.parseXmlToJson(str);
				rtnMap = getRtnMap("200000", "Success", data);
			} 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());
		} catch (DocumentException e) {
			e.printStackTrace();
			logger.error("HttpClient Request IOException!" + e.getMessage(), e);
			rtnMap = getRtnMap("200444", "Send Exception", "Send IOException"
													+ e.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;
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值