最近項目上面遇到和App對接,測試庫他們使用的是 HTTP,可是正式庫使用的是 HTTPS。以前沒有作過,在網上找過好多文章,最後仍是借鑑別人的,本身從新封裝以後纔在項目上面使用。
httpclient-4.3.1.jar
下面給出忽略證書的方式,由於App對接又不能給證書,而且證書是經過CA驗證,只好經過此種方式去試試:json
private static final int SOCKET_TIME_OUT = 60000; // 設置讀取超時 private static final int CONNECT_TIME_OUT = 60000; // 設置鏈接超時 /** * 設置請求的參數值 * @return */ private static RequestConfig getRequestConfig() { return RequestConfig.custom().setSocketTimeout(SOCKET_TIME_OUT).setConnectTimeout(CONNECT_TIME_OUT).build(); } /** * 設置參數列表 * @param param * @return */ private static List<NameValuePair> createParam(Map<String, Object> param) { List<NameValuePair> nvps = new ArrayList <NameValuePair>(); if(param != null) { for(String k : param.keySet()) { nvps.add(new BasicNameValuePair(k, param.get(k).toString())); } } return nvps; }
2.1建立鏈接對象:
/** * 建立一個SSL信任全部證書的httpClient對象 * @return */ public static CloseableHttpClient createSSLInsecureClient() { try { SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() { // 默認信任全部證書 public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException { return true; } }).build(); // AllowAllHostnameVerifier: 這種方式不對主機名進行驗證,驗證功能被關閉,是個空操做(域名驗證) SSLConnectionSocketFactory sslcsf = new SSLConnectionSocketFactory(sslContext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); return HttpClients.custom().setSSLSocketFactory(sslcsf).build(); } catch (KeyManagementException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (KeyStoreException e) { e.printStackTrace(); } //若是建立失敗,就建立一個默認的Http的鏈接 return HttpClients.createDefault(); }
2.2調用方法:
/** * 無需本地證書keyStore的SSL https帶參數請求 * post K - V 格式的數據 * @param url * @param paramsMap * @param encoding * @return */ public static String postSSLParams(String url, Map<String, Object> params, Map<String, Object> headers) { //建立一個信任的鏈接 CloseableHttpClient httpClient = createSSLInsecureClient(); //發送請求的實體類 HttpPost httpPost = new HttpPost(url); //接收返回值 StringBuilder sb = new StringBuilder(); BufferedReader br = null; try { // 設置客戶端請求的頭參數getParams已通過時,如今用requestConfig對象替換 httpPost.setConfig(getRequestConfig()); //設置請求的頭信息 Set<String> keys = headers.keySet(); for (String key : keys) { httpPost.setHeader(key, headers.get(key).toString()); } //這個是設置請求的類型,這個可能須要重點注意下,須要看對方接收的是什麼 httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded"); //添加參數, 設置編碼格式 httpPost.setEntity(new UrlEncodedFormEntity( createParam(params) , Charset.forName("utf-8"))); //發送請求 HttpResponse response = httpClient.execute(httpPost); //接收返回值 HttpEntity httpEntity = response.getEntity(); //返回值處理 br = new BufferedReader(new InputStreamReader(httpEntity.getContent(),"utf-8")); String s = null; while((s=br.readLine())!=null){ sb.append(s); } } catch (UnsupportedEncodingException e) { throw new RuntimeException("指定的編碼集不對,您目前指定的編碼集是:" + "utf-8"); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { throw new RuntimeException("讀取流文件異常",e); }catch (Exception e) { throw new RuntimeException("通信未知系統異常",e); }finally{ if(br != null){ try { br.close(); } catch (IOException e) { e.printStackTrace(); } } } return sb.toString(); }
3.1 發送 HTTP,K-V形式
/** * 發送 POST 請求(HTTP),K-V形式 * @param url * @param param * @return * @throws Exception */ public static String defaultPost(String url, Map<String, Object> param) throws Exception{ String returnString = ""; CloseableHttpClient client = HttpClients.createDefault(); CloseableHttpResponse response = null; //設置字符集的兩種方式 //new UrlEncodedFormEntity( createParam(params), Charset.forName("UTF-8")) HttpEntity entity = new UrlEncodedFormEntity(createParam(param), Consts.UTF_8); try { HttpPost httpPost = new HttpPost(url); httpPost.setConfig(getRequestConfig()); httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded"); httpPost.setEntity(entity); response = client.execute(httpPost); returnString = EntityUtils.toString(response.getEntity(), "UTF-8"); EntityUtils.consume(response.getEntity()); //關閉請求 return returnString; } catch(Exception e) { e.printStackTrace(); } return returnString; }
3.2 發送 HTTP,JSON形式
/** * 發送 POST 請求(HTTP),JSON形式 * @param url 調用的地址 * @param jsonParams 調用的參數 * @return * @throws Exception */ public static String postJson(String url, String jsonParams) throws Exception { //建立一個默認的鏈接對象 CloseableHttpClient httpClient = HttpClients.createDefault(); CloseableHttpResponse response = null; HttpPost httpPost = new HttpPost(url); String httpStr; try { StringEntity entity = new StringEntity(jsonParams); entity.setContentEncoding("UTF-8"); entity.setContentType("application/json"); httpPost.setEntity(entity); response = httpClient.execute(httpPost); httpStr = EntityUtils.toString(response.getEntity(), "UTF-8"); } finally { if (response != null) { EntityUtils.consume(response.getEntity()); } } return httpStr; }
另外幾點說明下:安全
1.因爲我以爲get請求的方式實在是不安全,就沒有去研究get。 2.以上是我在項目上面使用的,沒有添加所有的代碼,可是對應的方法都是可使用的。