Http工具类

  • import java.io.BufferedReader;
  • import java.io.IOException;
  • import java.io.InputStream;
  • import java.io.InputStreamReader;
  • import java.io.UnsupportedEncodingException;
  • import java.math.BigDecimal;
  • import java.security.KeyManagementException;
  • import java.security.NoSuchAlgorithmException;
  • import java.security.cert.CertificateException;
  • import java.security.cert.X509Certificate;
  • import java.util.ArrayList;
  • import java.util.HashMap;
  • import java.util.Iterator;
  • import java.util.List;
  • import java.util.Map;
  • import java.util.Map.Entry;
  • import java.util.Set;
  • import javax.net.ssl.SSLContext;
  • import javax.net.ssl.SSLException;
  • import javax.net.ssl.SSLSession;
  • import javax.net.ssl.SSLSocket;
  • import javax.net.ssl.TrustManager;
  • import javax.net.ssl.X509TrustManager;
  • import javax.servlet.http.HttpServletRequest;
  • import org.apache.http.HttpEntity;
  • import org.apache.http.HttpResponse;
  • import org.apache.http.HttpStatus;
  • import org.apache.http.NameValuePair;
  • import org.apache.http.client.ClientProtocolException;
  • import org.apache.http.client.HttpClient;
  • import org.apache.http.client.config.RequestConfig;
  • import org.apache.http.client.entity.UrlEncodedFormEntity;
  • import org.apache.http.client.methods.HttpDelete;
  • import org.apache.http.client.methods.HttpGet;
  • import org.apache.http.client.methods.HttpPost;
  • import org.apache.http.conn.scheme.Scheme;
  • import org.apache.http.conn.ssl.SSLSocketFactory;
  • import org.apache.http.conn.ssl.X509HostnameVerifier;
  • import org.apache.http.entity.StringEntity;
  • import org.apache.http.impl.client.DefaultHttpClient;
  • import org.apache.http.message.BasicNameValuePair;
  • import org.apache.http.util.EntityUtils;
  • import org.slf4j.Logger;
  • import org.slf4j.LoggerFactory;
  • /**
    • HTTP工具类
    • @author ycye
  • */
  • public class HttpUtils {
  • private static Logger logger = LoggerFactory.getLogger(HttpUtils.class);
  • private static final int OSB_TIME_OUT=20;
  • /**
    • HTTPGET
    • @param url
    • @param paramsMap
    • @param encoding
    • @return
  • */
  • public final static String httpGet(String url, Map paramsMap, String encoding) throws Exception{
  • Map headerMap = new HashMap();
  • headerMap.put("Content-Type", "application/x-www-form-urlencoded; charset=" + encoding);
  • return get(url, paramsMap, headerMap, encoding, url != null && url.startsWith("https:") ? "https" : "http");
  • }
  • /**
    • HTTPSGET
    • @param url
    • @param paramsMap
    • @param encoding
    • @return
  • */
  • public final static String httpsGet(String url, Map paramsMap, String encoding) throws Exception{
  • Map headerMap = new HashMap();
  • headerMap.put("Content-Type", "application/x-www-form-urlencoded; charset=" + encoding);
  • return get(url, paramsMap, headerMap, encoding, url != null && url.startsWith("https:") ? "https" : "http");
  • }
  • /**
    • HTTPSPOST
    • @param url
    • @param paramsMap
    • @param encoding
    • @return
  • */
  • public final static String httpPost(String url, Map paramsMap, String encoding) {
  • Map headerMap = new HashMap();
  • headerMap.put("Content-Type", "application/x-www-form-urlencoded; charset=" + encoding);
  • // 组装参数
  • List params = parseMap2BasicForm(paramsMap);
  • UrlEncodedFormEntity entity = null;
  • try {
  • entity = new UrlEncodedFormEntity(params, encoding);
  • } catch (UnsupportedEncodingException e) {
  • logger.error("httpPost fail" + e.getMessage(), e);
  • }
  • return post(url, headerMap, entity, encoding, url != null && url.startsWith("https:") ? "https" : "http");
  • }
  • /**
    • HTTPSPOST
    • @param url
    • @param paramsMap
    • @param headerMap
    • @param encoding
    • @return
  • */
  • public final static String httpPost(String url, Map paramsMap,Map headerMap, String encoding) {
  • headerMap.put("Content-Type", "application/x-www-form-urlencoded; charset=" + encoding);
  • // 组装参数
  • List params = parseMap2BasicForm(paramsMap);
  • UrlEncodedFormEntity entity = null;
  • try {
  • entity = new UrlEncodedFormEntity(params, encoding);
  • } catch (UnsupportedEncodingException e) {
  • logger.error("httpPost fail" + e.getMessage(), e);
  • }
  • return post(url, headerMap, entity, encoding, url != null && url.startsWith("https:") ? "https" : "http");
  • }
  • /**
    • HTTPSPOST
    • @param url
    • @param paramsMap
    • @param encoding
    • @return
  • */
  • public final static String httpsPost(String url, Map paramsMap, String encoding) {
  • return httpPost(url, paramsMap, encoding);
  • }
  • /**
    • HTTPSPOST JSON 改为根据URL的前面几个字母(协议),来进行http或https调用。
    • @param url
    • @param paramJson
    • @param headerMap
    • @param encoding
    • @return
  • */
  • public final static String httpsPostJson(String url, String paramJson,Map headerMap, String encoding) {
  • headerMap.put("Content-Type", "application/json; charset=" + encoding);
  • // 组装参数
  • StringEntity entity = null;
  • try {
  • logger.debug("send post data:" + paramJson);
  • entity = new StringEntity(paramJson, encoding);
  • entity.setContentType("application/x-www-form-urlencoded");
  • } catch (Exception e) {
  • logger.error("组装参数失败" + e.getMessage(), e);
  • }
  • return post(url, headerMap, entity, encoding, url != null && url.startsWith("https:") ? "https" : "http");
  • }
  • /**
    • HTTPSPOST JSON 改为根据URL的前面几个字母(协议),来进行http或https调用。
  • *
    • @param url
    • @param paramJson
    • @param headerMap
    • @param encoding
    • @return
  • */
  • public final static HttpResponse nativeHttpsPostJson(String url, String paramJson,Map headerMap, String encoding) {
  • headerMap.put("Content-Type", "application/json; charset=" + encoding);
  • // 组装参数
  • StringEntity entity = null;
  • try {
  • logger.debug("send post data:" + paramJson);
  • entity = new StringEntity(paramJson, encoding);
  • } catch (Exception e) {
  • logger.error("组装参数失败" + e.getMessage(), e);
  • }
  • return nativePost(url, headerMap, entity, encoding, url != null && url.startsWith("https:") ? "https" : "http");
  • }
  • /**
    • HTTPSPOST JSON 改为根据URL的前面几个字母(协议),来进行http或https调用。
    • @param url
    • @param paramJson
    • @param encoding
    • @return
  • */
  • public final static String httpsPostJson(String url, String paramJson, String encoding) {
  • Map headerMap = new HashMap();
  • headerMap.put("Content-Type", "application/json; charset=" + encoding);
  • // 组装参数
  • StringEntity entity = null;
  • try {
  • logger.debug("send post data:" + paramJson);
  • entity = new StringEntity(paramJson, encoding);
  • } catch (Exception e) {
  • logger.error("组装参数失败" + e.getMessage(), e);
  • }
  • return post(url, headerMap, entity, encoding, url != null && url.startsWith("https:") ? "https" : "http");
  • }
  • /**
    • HTTPSPOST JSON 改为根据URL的前面几个字母(协议),来进行http或https调用。
    • @param url
    • @param encoding
    • @return
  • */
  • public final static String httpsPostJson(String url, String encoding) {
  • Map headerMap = new HashMap();
  • headerMap.put("Content-Type", "application/json; charset=" + encoding);
  • return post(url, headerMap, null, encoding, url != null && url.startsWith("https:") ? "https" : "http");
  • }
  • /**
    • HTTPSDELETE 改为根据URL的前面几个字母(协议),来进行http或https调用。
    • @param url
    • @param encoding
    • @return
  • */
  • public final static HttpResponse httpsDelete(String url, String encoding) {
  • Map headerMap = new HashMap();
  • headerMap.put("Content-Type", "application/json; charset=" + encoding);
  • return delete(url, headerMap, encoding, url != null && url.startsWith("https:") ? "https" : "http");
  • }
  • /**
    • HTTP POST XML
    • @param url
    • @param requestXML
    • @param encoding
    • @param soapAction
    • @return
    • @throws Exception
  • */
  • public final static String httpPostXml(String url, String requestXML, String encoding, String soapAction)
  • throws Exception {
  • Map headerMap = new HashMap();
  • headerMap.put("Content-Type", "text/xml; charset=" + encoding);
  • headerMap.put("Accept", "application/soap+xml, application/dime, multipart/related, text/*");
  • // headerMap.put("User-Agent","Axis/1.4");
  • // headerMap.put("Cache-Control","no-cache");
  • // headerMap.put("Pragma","no-cache");
  • // headerMap.put("SOAPAction",soapAction);
  • // headerMap.put("Content-Length",requestXML.getBytes().length + "");
  • // 组装参数
  • StringEntity entity = null;
  • try {
  • entity = new StringEntity(requestXML, encoding);
  • } catch (Exception e) {
  • logger.error("httpPostXml error : ", e);
  • }
  • return post(url, headerMap, entity, encoding, url != null && url.startsWith("https:") ? "https" : "http");
  • }
  • /**
    • GET
    • @param url
    • @param paramsMap
    • @param headerMap
    • @param encoding
    • @param type http or https
    • @return
  • */
  • @SuppressWarnings("deprecation")
  • private final static String get(String url, Map paramsMap, Map headerMap,
  • String encoding, String type) throws Exception{
  • String result = "";
  • // 组装参数
  • String paramStr = "";
  • Set> paramEntries = paramsMap.entrySet();
  • for (Entry entry : paramEntries) {
  • Object key = entry.getKey();
  • Object val = entry.getValue();
  • paramStr += paramStr = "&" + key + "=" + val;
  • }
  • if (!"".equals(paramStr)) {
  • paramStr = paramStr.replaceFirst("&", "?");
  • url += paramStr;
  • }
  • // 创建一个httpGet请求
  • HttpGet request = new HttpGet(url);
  • // 组装header参数
  • Set> headerEntries = headerMap.entrySet();
  • for (Entry entry : headerEntries) {
  • request.setHeader(String.valueOf(entry.getKey()), String.valueOf(entry.getValue()));
  • }
  • try {
  • // 创建一个htt客户端
  • HttpClient httpClient = "https".equals(type) ? getHttpsClient() : new DefaultHttpClient();
  • RequestConfig requestConfig =
  • RequestConfig.custom().setSocketTimeout(110001).setConnectTimeout(110001).build();
  • request.setConfig(requestConfig);
  • logger.debug("execute http get request,url:"+url);
  • // 接受客户端发回的响应
  • HttpResponse httpResponse = httpClient.execute(request);
  • int statusCode = httpResponse.getStatusLine().getStatusCode();
  • if (statusCode == HttpStatus.SC_OK) {
  • logger.debug("接口:"+url+" 返回数据:"+result);
  • // 得到客户段响应的实体内容
  • result = EntityUtils.toString(httpResponse.getEntity(), encoding);
  • } else {
  • logger.error("URL:" + url + "\tStatusCode:" + statusCode);
  • }
  • } catch (Exception e) {
  • logger.error(e.getMessage(), e);
  • throw e;
  • }
  • return result;
  • }
  • /**
    • delete
    • @param url
    • @param headerMap
    • @param encoding
    • @param type
    • @return
  • */
  • private final static HttpResponse delete(String url, Map headerMap, String encoding, String type) {
  • String result = "";
  • HttpResponse httpResponse = null;
  • // 创建一个httpGet请求
  • HttpDelete request = null;
  • // 创建一个htt客户端
  • HttpClient httpClient = null;
  • try {
  • // 创建一个HttpDelete请求
  • request = new HttpDelete(url);
  • // 组装header参数
  • Set> headerEntries = headerMap.entrySet();
  • for (Entry entry : headerEntries) {
  • request.setHeader(String.valueOf(entry.getKey()), String.valueOf(entry.getValue()));
  • }
  • logger.debug("Post Data to [" + url + "] ");
  • // 创建一个htt客户端
  • httpClient = "https".equals(type) ? getHttpsClient() : new DefaultHttpClient();
  • RequestConfig requestConfig =
  • RequestConfig.custom().setSocketTimeout(6010001).setConnectTimeout(6010001).build();
  • request.setConfig(requestConfig);
  • // 接受客户端发回的响应
  • httpResponse = httpClient.execute(request);
  • // 接受客户端发回的响应
  • int statusCode = httpResponse.getStatusLine().getStatusCode();
  • if (statusCode == HttpStatus.SC_OK) {
  • // 得到客户段响应的实体内容
  • result = EntityUtils.toString(httpResponse.getEntity(), encoding);
  • }
  • } catch (Exception e) {
  • request.abort();
  • String errordebug = String.format("httpclient delete failed:\nUrl=%s\nError=%s", url,
  • e.toString());
  • logger.error(errordebug, e);
  • } finally {
  • // -------- 2016-1-19 是否链接 start
  • // 判断request是否等于null
  • if (request != null) {
  • try {
  • // 释放链接
  • request.releaseConnection();
  • logger.debug("close request");
  • } catch (Exception e) {
  • logger.error("close request fail", e);
  • }
  • }
  • // 判断httpclient是否为null
  • if (httpClient != null) {
  • try {
  • // 关闭链接
  • httpClient.getConnectionManager().shutdown();
  • logger.debug("close httpClient");
  • } catch (Exception e) {
  • logger.error("close httpClient fail", e);
  • }
  • }
  • // -------- 2016-1-19 是否链接 start
  • }
  • return httpResponse;
  • }
  • /**
    • POST
    • @param url
    • @param headerMap
    • @param requestEntity
    • @param encoding
    • @param type
    • @return
  • */
  • private final static String post(String url, Map headerMap, HttpEntity requestEntity,
  • String encoding, String type) {
  • // String result = "";
  • HttpResponse httpResponse = null;
  • // 创建一个httpGet请求
  • HttpPost request = null;
  • // 创建一个htt客户端
  • HttpClient httpClient = null;
  • String result="";
  • try {
  • // 创建一个httpGet请求
  • request = new HttpPost(url);
  • // 组装header参数
  • Set> headerEntries = headerMap.entrySet();
  • for (Entry entry : headerEntries) {
  • request.setHeader(String.valueOf(entry.getKey()), String.valueOf(entry.getValue()));
  • }
  • // 设置参数
  • request.setEntity(requestEntity);
  • logger.debug("Post Data to [" + url + "] ");
  • // 创建一个htt客户端
  • httpClient = "https".equals(type) ? getHttpsClient() : new DefaultHttpClient();
  • RequestConfig requestConfig =
  • RequestConfig.custom().setSocketTimeout(1601000).setConnectTimeout(1601000).build();
  • request.setConfig(requestConfig);
  • // 接受客户端发回的响应
  • httpResponse = httpClient.execute(request);
  • // 接受客户端发回的响应
  • int statusCode = httpResponse.getStatusLine().getStatusCode();
  • if (statusCode == HttpStatus.SC_OK) {
  • // 得到客户段响应的实体内容
  • result = EntityUtils.toString(httpResponse.getEntity(), encoding);
  • logger.debug("接口:"+url+" 返回数据:"+result);
  • }else {
  • logger.error("http post URL:" + url + "\tStatusCode:" + statusCode);
  • }
  • } catch (Exception e) {
  • request.abort();
  • String errordebug = String.format("httpclient post failed:\nUrl=%s\nError=%s", url, e.toString());
  • logger.error(errordebug, e);
  • throw new RuntimeException(e);
  • } finally {
  • // -------- 2016-1-19 是否链接 start
  • // 判断request是否等于null
  • if (request != null) {
  • try {
  • // 释放链接
  • request.releaseConnection();
  • logger.debug("close request");
  • } catch (Exception e) {
  • logger.error("close request fail", e);
  • }
  • }
  • // 判断httpclient是否为null
  • if (httpClient != null) {
  • try {
  • // 关闭链接
  • httpClient.getConnectionManager().shutdown();
  • logger.debug("close httpClient");
  • } catch (Exception e) {
  • logger.error("close httpClient fail", e);
  • }
  • }
  • // -------- 2016-1-19 是否链接 start
  • }
  • return result;
  • }
  • /**
  • *
    • @param url
    • @param headerMap
    • @param requestEntity
    • @param encoding
    • @param type
    • @return
  • */
  • private final static HttpResponse nativePost(String url, Map headerMap, HttpEntity requestEntity,
  • String encoding, String type) {
  • // String result = "";
  • HttpResponse httpResponse = null;
  • // 创建一个httpGet请求
  • HttpPost request = null;
  • // 创建一个htt客户端
  • HttpClient httpClient = null;
  • String result="";
  • try {
  • // 创建一个httpGet请求
  • request = new HttpPost(url);
  • // 组装header参数
  • Set> headerEntries = headerMap.entrySet();
  • for (Entry entry : headerEntries) {
  • request.setHeader(String.valueOf(entry.getKey()), String.valueOf(entry.getValue()));
  • }
  • // 设置参数
  • request.setEntity(requestEntity);
  • logger.debug("Post Data to [" + url + "] ");
  • // 创建一个htt客户端
  • httpClient = "https".equals(type) ? getHttpsClient() : new DefaultHttpClient();
  • RequestConfig requestConfig =
  • RequestConfig.custom().setSocketTimeout(1601000).setConnectTimeout(1601000).build();
  • request.setConfig(requestConfig);
  • // 接受客户端发回的响应
  • httpResponse = httpClient.execute(request);
  • result = EntityUtils.toString(httpResponse.getEntity(), encoding);
  • logger.debug("接口:"+url+" 返回数据:"+result);
  • } catch (Exception e) {
  • request.abort();
  • String errordebug = String.format("httpclient post failed:\nUrl=%s\nError=%s", url, e.toString());
  • logger.error(errordebug, e);
  • throw new RuntimeException(e);
  • } finally {
  • // -------- 2016-1-19 是否链接 start
  • // 判断request是否等于null
  • if (request != null) {
  • try {
  • // 释放链接
  • request.releaseConnection();
  • logger.debug("close request");
  • } catch (Exception e) {
  • logger.error("close request fail", e);
  • }
  • }
  • // 判断httpclient是否为null
  • if (httpClient != null) {
  • try {
  • // 关闭链接
  • httpClient.getConnectionManager().shutdown();
  • logger.debug("close httpClient");
  • } catch (Exception e) {
  • logger.error("close httpClient fail", e);
  • }
  • }
  • // -------- 2016-1-19 是否链接 start
  • }
  • return httpResponse;
  • }
  • /**
    • 封装MAP格式的参数到BasicNameValuePair中
    • @param paramsMap
    • @return
  • */
  • private static final List parseMap2BasicForm(Map paramsMap) {
  • List params = new ArrayList();;
  • if (paramsMap != null && paramsMap.size() > 0) {
  • Iterator it = paramsMap.keySet().iterator();
  • String keyTmp = null;
  • while (it.hasNext()) {
  • keyTmp = it.next();
  • params.add(new BasicNameValuePair(keyTmp, paramsMap.get(keyTmp)));
  • }
  • }
  • return params;
  • }
  • /**
    • 取已配置的HttpsClient
    • @return
    • @throws NoSuchAlgorithmException
    • @throws KeyManagementException
  • */
  • private final static DefaultHttpClient getHttpsClient() throws NoSuchAlgorithmException, KeyManagementException {
  • // 创建默认的httpClient实例
  • DefaultHttpClient httpClient = new DefaultHttpClient();
  • X509TrustManager xtm = new X509TrustManager() { // 创建TrustManager
  • @Override
  • public void checkClientTrusted(X509Certificate[] chain, String authType)
  • throws CertificateException {}
  • @Override
  • public void checkServerTrusted(X509Certificate[] chain, String authType)
  • throws CertificateException {}
  • @Override
  • public X509Certificate[] getAcceptedIssuers() {
  • return null;
  • }
  • };
  • X509HostnameVerifier hostnameVerifier = new X509HostnameVerifier() {
  • @Override
  • public boolean verify(String hostname, SSLSession session) {
  • return false;
  • }
  • @Override
  • public void verify(String arg0, SSLSocket arg1) throws IOException {}
  • @Override
  • public void verify(String arg0, X509Certificate arg1) throws SSLException {}
  • @Override
  • public void verify(String arg0, String[] arg1, String[] arg2) throws SSLException {}
  • };
  • SSLContext ctx;
  • try {
  • // ctx = SSLContext.getInstance("SSL", "SunJSSE");
  • ctx = SSLContext.getInstance("TLS");
  • // 使用TrustManager来初始化该上下文,TrustManager只是被SSL的Socket所使用
  • ctx.init(null, new TrustManager[] {xtm}, new java.security.SecureRandom());
  • // 创建SSLSocketFactory
  • SSLSocketFactory socketFactory = new SSLSocketFactory(ctx, hostnameVerifier);
  • // 通过SchemeRegistry将SSLSocketFactory注册到我们的HttpClient上
  • httpClient.getConnectionManager().getSchemeRegistry().register(new Scheme("https", 443, socketFactory));
  • } catch (Exception e) {
  • }
  • return httpClient;
  • }
  • /**
    • http get string from remote machine
    • @param url
    • @return
    • @throws IOException
    • @throws ClientProtocolException
  • */
  • public static String getNetString(String url) throws IOException, ClientProtocolException {
  • String result = "";
  • HttpClient httpclient = new DefaultHttpClient();
  • HttpGet get = new HttpGet(url);
  • HttpResponse httpResponse = httpclient.execute(get);
  • int statusCode = httpResponse.getStatusLine().getStatusCode();
  • if (statusCode == HttpStatus.SC_OK) {
  • // 得到客户段响应的实体内容
  • result = EntityUtils.toString(httpResponse.getEntity(), "utf-8");
  • }
  • get.abort();
  • return result;
  • }
  • // 调用osb
  • public static String invokeOsbInteface(String url, Map paramMap) throws Exception {
  • try {
  • HttpClient httpclient = new DefaultHttpClient();
  • HttpPost p = new HttpPost(url);
  • //p.addHeader("appid", paramMap.get("appid").toString());
  • // p.addHeader("appkey", paramMap.get("appkey").toString());
  • // paramMap.remove("appid");
  • // paramMap.remove("appkey");
  • List params = new ArrayList();
  • Iterator iter = paramMap.keySet().iterator();
  • while (iter.hasNext()) {
  • String key = iter.next();
  • params.add(new BasicNameValuePair(key, (String) paramMap.get(key)));
  • }
  • UrlEncodedFormEntity entity2 = new UrlEncodedFormEntity(params, "UTF-8");
  • p.setEntity(entity2);
  • RequestConfig requestConfig =
  • RequestConfig.custom().setSocketTimeout(OSB_TIME_OUT)
  • .setConnectTimeout(OSB_TIME_OUT).build();
  • p.setConfig(requestConfig);
  • HttpResponse response = httpclient.execute(p);
  • HttpEntity entity = response.getEntity();
  • if (entity != null) {
  • String result = EntityUtils.toString(response.getEntity(), "utf-8");
  • return result;
  • }
  • } catch (Exception e) {
  • logger.error(":失败" + e.getMessage(), e);
  • throw e;
  • }
  • return null;
  • }
  • public static String getParame(HttpServletRequest request) throws Exception {
  • StringBuffer sb = new StringBuffer() ;
  • InputStream is = request.getInputStream();
  • BufferedReader br = new BufferedReader(new InputStreamReader(is,"utf-8"));
  • String s = "" ;
  • while((s=br.readLine())!=null){
  • sb.append(s) ;
  • }
  • return sb.toString();
  • }
  • }

名称栏目:Http工具类
当前网址:http://ybzwz.com/article/pdsepp.html