開始前的準備:
需要https://XXXXX下的訪問認證儲存為cer檔案。
基礎代碼:
1、參考兩篇文章:
http://blog.csdn.net/liuxiaoshuang002/article/details/51955020 用來判斷是否為空白
http://blog.csdn.net/liuxiaoshuang002/article/details/51955031 比較對象是否相等
2、請求後返回的實體 HttpResponseEntity 詳細代碼如下:
package com.gj5u.publics.util.httpweb;import java.util.Map;/** * 擷取內容實體 * @author Rex * */public class HttpResponseEntity{ private Map<String,String> resHeaders; private String httpBody; private String statusLine; private String ErrMessage; /** * Header資訊 * @return Header資訊 */ public Map<String, String> getResHeaders() { return resHeaders; } /** * Header資訊 * @param resHeaders Header資訊 */ public void setResHeaders(Map<String, String> resHeaders) { this.resHeaders = resHeaders; } /** * Body 內容 * @return Body 內容 */ public String getHttpBody() { return httpBody; } /** * Body 內容 * @param httpBody Body 內容 */ public void setHttpBody(String httpBody) { this.httpBody = httpBody; } /** * 狀態行 * @return 狀態行 */ public String getStatusLine() { return statusLine; } /** * 狀態行 * @param statusLine 狀態行 */ public void setStatusLine(String statusLine) { this.statusLine = statusLine; } public String getErrMessage() { return ErrMessage; } public void setErrMessage(String errMessage) { ErrMessage = errMessage; } }
關於請求的詳細代碼
package com.gj5u.publics.util.httpweb;import java.io.BufferedReader;import java.io.InputStream;import java.io.InputStreamReader;import java.util.HashMap;import java.util.Map;import org.apache.http.Header;import org.apache.http.HttpEntity;import org.apache.http.client.config.RequestConfig;import org.apache.http.client.methods.CloseableHttpResponse;import org.apache.http.client.methods.HttpDelete;import org.apache.http.client.methods.HttpGet;import org.apache.http.client.methods.HttpHead;import org.apache.http.client.methods.HttpOptions;import org.apache.http.client.methods.HttpPatch;import org.apache.http.client.methods.HttpPost;import org.apache.http.client.methods.HttpPut;import org.apache.http.client.methods.HttpTrace;import org.apache.http.entity.StringEntity;import org.apache.http.impl.client.CloseableHttpClient;import cn.ava.publics.util.EmptyUtil;import cn.ava.publics.util.EqualsUtil;public class MyHttpsConn{ // [start] 屬性定義 /* * 請求的URL */ private String Requrl; private String WebCerPath; private Map<String, String> ReqHeaderKV; /** * Http請求方式 * * @author Rex * */ public enum HttpMethod { POST, GET, DELETE, HEAD, PATCH, TRACE, OPTIONS, PUT } public String getRequrl() { return Requrl; } public String getWebCerPath() { return WebCerPath; } public Map<String, String> getReqHeaderKV() { return ReqHeaderKV; } // [end] /** * 初始化 * * @param url * 請求URL * @param cerpath * 憑證路徑 * @param cerpwd * 認證密碼 */ public MyHttpsConn(String url, String cerpath) { Requrl = url; WebCerPath = cerpath; } public HttpResponseEntity SendHttps(HttpMethod Method, Map<String, String> Parameters, Map<String, String> Header, String Body, String[] HeaderField) { HttpPost httpPost = new HttpPost(Requrl); HttpGet httpGet = new HttpGet(Requrl); HttpDelete httpDelete = new HttpDelete(Requrl); HttpHead httpHead = new HttpHead(Requrl); HttpPatch httpPatch = new HttpPatch(Requrl); HttpTrace httpTrace = new HttpTrace(Requrl); HttpOptions httpOptions = new HttpOptions(Requrl); HttpPut httpPut = new HttpPut(Requrl); // 1、將URL參數寫入URL中 if (EmptyUtil.isNotEmpty(Parameters)) { String pvalue = ""; for (Map.Entry<String, String> entry : Parameters.entrySet()) { if (pvalue != "") { pvalue += "&"; } pvalue += entry.getKey() + "=" + entry.getValue(); } if (pvalue != "") { this.Requrl += "?" + pvalue; } } // 2、將header寫入header中 if (EmptyUtil.isNotEmpty(Header)) { for (Map.Entry<String, String> entry : Header.entrySet()) { if (EqualsUtil.ObjEquals(HttpMethod.POST, Method)) { httpPost.setHeader(entry.getKey(), entry.getValue()); } else if (EqualsUtil.ObjEquals(HttpMethod.GET, Method)) { httpGet.setHeader(entry.getKey(), entry.getValue()); } else if (EqualsUtil.ObjEquals(HttpMethod.DELETE, Method)) { httpDelete.setHeader(entry.getKey(), entry.getValue()); } else if (EqualsUtil.ObjEquals(HttpMethod.HEAD, Method)) { httpHead.setHeader(entry.getKey(), entry.getValue()); } else if (EqualsUtil.ObjEquals(HttpMethod.OPTIONS, Method)) { httpOptions.setHeader(entry.getKey(), entry.getValue()); } else if (EqualsUtil.ObjEquals(HttpMethod.PATCH, Method)) { httpPatch.setHeader(entry.getKey(), entry.getValue()); } else if (EqualsUtil.ObjEquals(HttpMethod.PUT, Method)) { httpPut.setHeader(entry.getKey(), entry.getValue()); } else if (EqualsUtil.ObjEquals(HttpMethod.TRACE, Method)) { httpTrace.setHeader(entry.getKey(), entry.getValue()); } } } // 3、 請求訊息體設定 HttpEntity entity = new StringEntity(Body, "UTF-8"); if (EqualsUtil.ObjEquals(HttpMethod.POST, Method)) { httpPost.setEntity(entity); } else if (EqualsUtil.ObjEquals(HttpMethod.PATCH, Method)) { httpPatch.setEntity(entity); } else if (EqualsUtil.ObjEquals(HttpMethod.PUT, Method)) { httpPut.setEntity(entity); } SSLSocketFactoryLoad.loadSSLSocketFactory(this.WebCerPath); HttpResponseEntity responseEntity = new HttpResponseEntity(); Boolean isHttps = this.Requrl.startsWith("https"); CloseableHttpClient httpclient = HttpClientConstructor.getHttpClient(isHttps); if (isHttps) { RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(30000).setConnectTimeout(30000).build();// 佈建要求和傳輸逾時時間 if (EqualsUtil.ObjEquals(HttpMethod.POST, Method)) { httpPost.setConfig(requestConfig); } else if (EqualsUtil.ObjEquals(HttpMethod.GET, Method)) { httpGet.setConfig(requestConfig); } else if (EqualsUtil.ObjEquals(HttpMethod.DELETE, Method)) { httpDelete.setConfig(requestConfig); } else if (EqualsUtil.ObjEquals(HttpMethod.HEAD, Method)) { httpHead.setConfig(requestConfig); } else if (EqualsUtil.ObjEquals(HttpMethod.OPTIONS, Method)) { httpOptions.setConfig(requestConfig); } else if (EqualsUtil.ObjEquals(HttpMethod.PATCH, Method)) { httpPatch.setConfig(requestConfig); } else if (EqualsUtil.ObjEquals(HttpMethod.PUT, Method)) { httpPut.setConfig(requestConfig); } else if (EqualsUtil.ObjEquals(HttpMethod.TRACE, Method)) { httpTrace.setConfig(requestConfig); } } CloseableHttpResponse responseBody = null; try { if (EqualsUtil.ObjEquals(HttpMethod.POST, Method)) { responseBody = httpclient.execute(httpPost); } else if (EqualsUtil.ObjEquals(HttpMethod.GET, Method)) { responseBody = httpclient.execute(httpGet); } else if (EqualsUtil.ObjEquals(HttpMethod.DELETE, Method)) { responseBody = httpclient.execute(httpDelete); } else if (EqualsUtil.ObjEquals(HttpMethod.HEAD, Method)) { responseBody = httpclient.execute(httpHead); } else if (EqualsUtil.ObjEquals(HttpMethod.OPTIONS, Method)) { responseBody = httpclient.execute(httpOptions); } else if (EqualsUtil.ObjEquals(HttpMethod.PATCH, Method)) { responseBody = httpclient.execute(httpPatch); } else if (EqualsUtil.ObjEquals(HttpMethod.PUT, Method)) { responseBody = httpclient.execute(httpPut); } else if (EqualsUtil.ObjEquals(HttpMethod.TRACE, Method)) { responseBody = httpclient.execute(httpTrace); } responseEntity = dealWithResponse(responseBody); ReqHeaderKV = new HashMap<String, String>(); for (Map.Entry<String, String> entry : responseEntity.getResHeaders().entrySet()) { if (EmptyUtil.isNotEmpty(HeaderField)) { for (int i = 0; i < HeaderField.length; i++) { if (EqualsUtil.StringEquals(entry.getKey(), HeaderField[i], false)) { ReqHeaderKV.put(entry.getKey(), entry.getValue()); } } } else { ReqHeaderKV.put(entry.getKey(), entry.getValue()); } } } catch (Exception e) { responseEntity.setErrMessage("Send request failed.\n" + e.getMessage()); e.printStackTrace(); } finally { try { httpclient.close(); } catch (Exception e) { responseEntity.setErrMessage("httpclient closed failed.\n" + e.getMessage()); } } return responseEntity; } private HttpResponseEntity dealWithResponse(CloseableHttpResponse responseBody) { BufferedReader reader = null; HttpResponseEntity responseEntity = new HttpResponseEntity(); try { Header[] resHeaders = responseBody.getAllHeaders(); Map<String, String> resHeadersArray = new HashMap<String, String>(); for (int i = 0; i < resHeaders.length; i++) { resHeadersArray.put(resHeaders[i].getName(), resHeaders[i].getValue()); } responseEntity.setResHeaders(resHeadersArray); responseEntity.setStatusLine(new String(responseBody.getStatusLine().toString().getBytes("ISO-8859-1"), "UTF-8")); InputStream content = responseBody.getEntity().getContent(); reader = new BufferedReader(new InputStreamReader(content, "UTF-8")); String line = null; StringBuilder strBuffer = new StringBuilder(); while ((line = reader.readLine()) != null) { strBuffer.append(line + "\n"); } responseEntity.setHttpBody(strBuffer.toString()); } catch (Exception e) { responseEntity.setErrMessage("Failed to analysing http response.\n" + e.getMessage()); } finally { try { reader.close(); } catch (Exception e) { responseEntity.setErrMessage("reader close error .\n" + e.getMessage()); } } return responseEntity; }}
使用方法
MyHttpsConn httpconn = new MyHttpsConn(httpsurl, CerPath); //請求的URL和憑證路徑 HttpResponseEntity httpentry = httpconn.SendHttps(HttpMethod.GET, Parameters, ReqHeader, Body,GetHeader);