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<String, String> paramsMap, String encoding) throws Exception{Map<String, String> headerMap = new HashMap<String, String>();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<String, String> paramsMap, String encoding) throws Exception{Map<String, String> headerMap = new HashMap<String, String>();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<String, String> paramsMap, String encoding) {Map<String, String> headerMap = new HashMap<String, String>();headerMap.put("Content-Type", "application/x-www-form-urlencoded; charset=" + encoding);// 组装参数List<BasicNameValuePair> 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<String, String> paramsMap,Map<String, String> headerMap, String encoding) {headerMap.put("Content-Type", "application/x-www-form-urlencoded; charset=" + encoding);// 组装参数List<BasicNameValuePair> 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<String, String> 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<String, String> 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<String, String> 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<String, String> headerMap = new HashMap<String, String>();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<String, String> headerMap = new HashMap<String, String>();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<String, String> headerMap = new HashMap<String, String>();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<String, String> headerMap = new HashMap<String, String>();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<String, String> paramsMap, Map<String, String> headerMap,String encoding, String type) throws Exception{String result = "";// 组装参数String paramStr = "";Set<Entry<String, String>> paramEntries = paramsMap.entrySet();for (Entry<String, String> 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<Entry<String, String>> headerEntries = headerMap.entrySet();for (Entry<String, String> 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<String, String> 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<Entry<String, String>> headerEntries = headerMap.entrySet();for (Entry<String, String> 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是否等于nullif (request != null) {try {// 释放链接request.releaseConnection();logger.debug("close request");} catch (Exception e) {logger.error("close request fail", e);}}// 判断httpclient是否为nullif (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<String, String> 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<Entry<String, String>> headerEntries = headerMap.entrySet();for (Entry<String, String> 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是否等于nullif (request != null) {try {// 释放链接request.releaseConnection();logger.debug("close request");} catch (Exception e) {logger.error("close request fail", e);}}// 判断httpclient是否为nullif (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<String, String> 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<Entry<String, String>> headerEntries = headerMap.entrySet();for (Entry<String, String> 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是否等于nullif (request != null) {try {// 释放链接request.releaseConnection();logger.debug("close request");} catch (Exception e) {logger.error("close request fail", e);}}// 判断httpclient是否为nullif (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<BasicNameValuePair> parseMap2BasicForm(Map<String, String> paramsMap) {List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();;if (paramsMap != null && paramsMap.size() > 0) {Iterator<String> 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@Overridepublic void checkClientTrusted(X509Certificate[] chain, String authType)throws CertificateException {}@Overridepublic void checkServerTrusted(X509Certificate[] chain, String authType)throws CertificateException {}@Overridepublic X509Certificate[] getAcceptedIssuers() {return null;}};X509HostnameVerifier hostnameVerifier = new X509HostnameVerifier() {@Overridepublic boolean verify(String hostname, SSLSession session) {return false;}@Overridepublic void verify(String arg0, SSLSocket arg1) throws IOException {}@Overridepublic void verify(String arg0, X509Certificate arg1) throws SSLException {}@Overridepublic 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());// 创建SSLSocketFactorySSLSocketFactory 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;}// 调用osbpublic static String invokeOsbInteface(String url, Map<String, Object> 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<NameValuePair> params = new ArrayList<NameValuePair>();Iterator<String> 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();}}
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。