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是否等於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<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是否等於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<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是否等於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<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
  • @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<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();
  • }
  • }
  • 發表評論
    所有評論
    還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
    相關文章