httpclient常規封裝的方法
阿新 • • 發佈:2018-10-31
<dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-compress</artifactId> <version>1.18</version> </dependency> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.4</version> </dependency> <dependency> <groupId>com.relevantcodes</groupId> <artifactId>extentreports</artifactId> <version>2.41.1</version> </dependency> <dependency> <groupId>com.vimalselvam</groupId> <artifactId>testng-extentsreport</artifactId> <version>1.3.1</version> </dependency> <dependency> <groupId>com.aventstack</groupId> <artifactId>extentreports</artifactId> <version>3.0.6</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.47</version> <scope>compile</scope> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.16.14</version> </dependency> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.3</version> </dependency>
package zhihuisystem.HttpClient_Test; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.security.KeyManagementException; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.cert.CertificateException;import java.security.cert.X509Certificate; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.StatusLine; import org.apache.http.client.ClientProtocolException;import org.apache.http.client.ResponseHandler; import org.apache.http.client.methods.CloseableHttpResponse; 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.NoopHostnameVerifier; import org.apache.http.conn.ssl.SSLConnectionSocketFactory; import org.apache.http.conn.ssl.SSLSocketFactory; import org.apache.http.conn.ssl.TrustSelfSignedStrategy; import org.apache.http.entity.BufferedHttpEntity; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.BasicResponseHandler; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.client.HttpClients; import org.apache.http.ssl.SSLContexts; import org.apache.http.util.EntityUtils; public class HttpClient_Utils { // 常規get請求 public static String Getmethod(String url) { CloseableHttpClient client = HttpClientBuilder.create().build(); HttpGet get = new HttpGet(url); CloseableHttpResponse respons1 = null; try { respons1 = client.execute(get); } catch (ClientProtocolException e1) { System.out.println("客戶端get請求異常"); e1.printStackTrace(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } // 切割字串 String result = respons1.getStatusLine().toString().split(" ")[1]; try { client.close();// 釋放資源 } catch (IOException e) { System.out.println("請求連線無法關閉,關注get方法!"); e.printStackTrace(); } return result; } // 常規P0ST請求 public static String HttpPostWithJson(String url, String json) { String returnValue = "這是預設返回值,介面呼叫失敗"; CloseableHttpClient httpClient = HttpClients.createDefault(); ResponseHandler<String> responseHandler = new BasicResponseHandler(); try { // 建立HttpClient物件 httpClient = HttpClients.createDefault(); // 建立httpPost物件 HttpPost httpPost = new HttpPost(url); // 給httpPost設定JSON格式的引數 StringEntity requestEntity = new StringEntity(json, "utf-8"); requestEntity.setContentEncoding("UTF-8"); httpPost.setHeader("Content-type", "application/json"); httpPost.setEntity(requestEntity); // 傳送HttpPost請求,獲取返回值 returnValue = httpClient.execute(httpPost, responseHandler); // 調介面獲取返回值,用此方法 } catch (Exception e) { System.out.println("請求返回值為空!"); e.printStackTrace(); } finally { try { httpClient.close(); } catch (IOException e) { System.out.println("請求連線無法關閉,關注post方法!"); e.printStackTrace(); } } // 第五步:處理返回值 return returnValue; } // 忽略證書的HTTPS請求 - get public static String HttpsGetIgnoreCertification(String url) throws NoSuchAlgorithmException, KeyManagementException, ClientProtocolException, IOException { // First create a trust manager that won't care. X509TrustManager trustManager = new X509TrustManager() { public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { // Don't do anything. } public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { // Don't do anything. } public X509Certificate[] getAcceptedIssuers() { // Don't do anything. return null; } }; // 現在將信任管理器放到SSLContext中。 SSLContext sslcontext = SSLContext.getInstance("SSL"); sslcontext.init(null, new TrustManager[] { trustManager }, null); SSLSocketFactory sf = new SSLSocketFactory(sslcontext); sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); DefaultHttpClient httpclient = new DefaultHttpClient(); httpclient.getConnectionManager().getSchemeRegistry().register(new Scheme("https", sf, 443)); HttpGet httpget = new HttpGet(url); // String result = ""; httpget.setHeader("Content-type", "application/json"); HttpResponse response = httpclient.execute(httpget); HttpEntity entity = response.getEntity(); EntityUtils.consume(entity); // String result1 = response.getStatusLine().toString(); // String result2 = response.getStatusLine().toString().split(" ")[2]; String result3 = response.getStatusLine().toString().split(" ")[1]; return result3; } // 忽略證書的HTTPS請求 - post public static String HttpsPostIgnoreCertification(String url, String requestData) throws NoSuchAlgorithmException, KeyManagementException, ClientProtocolException, IOException { // First create a trust manager that won't care. X509TrustManager trustManager = new X509TrustManager() { public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { // Don't do anything. } public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { // Don't do anything. } public X509Certificate[] getAcceptedIssuers() { // Don't do anything. return null; } }; // 現在將信任管理器放到SSLContext中。 SSLContext sslcontext = SSLContext.getInstance("SSL"); sslcontext.init(null, new TrustManager[] { trustManager }, null); SSLSocketFactory sf = new SSLSocketFactory(sslcontext); sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); DefaultHttpClient httpclient = new DefaultHttpClient(); httpclient.getConnectionManager().getSchemeRegistry().register(new Scheme("https", sf, 443)); HttpPost httpPost = new HttpPost(url); String result = ""; // httpPost.setHeader("Authorization", "basic " + "dGNsb3VkYWRtaW46dGNsb3VkMTIz"); httpPost.setHeader("Content-type", "application/json"); StringEntity reqEntity; // 將請求引數封裝成HttpEntity reqEntity = new StringEntity(requestData); BufferedHttpEntity bhe = new BufferedHttpEntity(reqEntity); httpPost.setEntity(bhe); HttpResponse response = httpclient.execute(httpPost); HttpEntity resEntity = response.getEntity(); InputStreamReader reader = new InputStreamReader(resEntity.getContent()); // 取記憶體資源 char[] buff = new char[1024]; int length = 0; while ((length = reader.read(buff)) != -1) { result += new String(buff, 0, length); } httpclient.close(); return result; // System.out.println(result); } // 啟用HTTPS攜帶證書GET請求 public static String HttpsforGet(String url, String keystore_PathFile, String keypwd) throws IOException, KeyManagementException, NoSuchAlgorithmException, KeyStoreException, CertificateException { HttpGet httpGet = new HttpGet(url); CloseableHttpClient httpClient = null; if (url.startsWith("https")) { // "E:\\White_testNG\\mock\\mock_https\\isa\\isa.keystor" File cert = new File(keystore_PathFile); String keystore = keypwd; // Trust own CA and all self-signed certs SSLContext sslcontext = SSLContexts.custom() .loadTrustMaterial(cert, keystore.toCharArray(), new TrustSelfSignedStrategy()).build(); // Allow TLSv1 protocol only SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" }, null, NoopHostnameVerifier.INSTANCE); httpClient = HttpClients.custom().setSSLSocketFactory(sslsf).build(); } else { httpClient = HttpClients.createDefault(); } try (CloseableHttpClient _httpClient = httpClient; CloseableHttpResponse res = _httpClient.execute(httpGet);) { StatusLine sl = res.getStatusLine(); // System.out.println(sl.toString().split(" ")[1]); String result = sl.toString().split(" ")[1]; /* * if (sl != null) { System.out.println(sl.getStatusCode()); StringBuilder * builder = new StringBuilder(); try (InputStream is = * res.getEntity().getContent(); InputStreamReader isr = new * InputStreamReader(is); BufferedReader br = new BufferedReader(isr);) { String * line = br.readLine(); while(line != null) { builder.append(line); line = * br.readLine(); } System.out.println("響應結果:" + builder.toString()); */ return result; } } // 啟用HTTPS攜帶證書post請求 public static String HttpsforPost(String url, String keystore_PathFile, String keypwd, String json) throws ClientProtocolException, IOException, KeyManagementException, NoSuchAlgorithmException, KeyStoreException, CertificateException { String returnValue = "這是預設返回值,介面呼叫失敗"; HttpPost httppost = new HttpPost(url); CloseableHttpClient httpClient = null; if (url.startsWith("https")) { File cert = new File(keystore_PathFile); String keystore = keypwd; // Trust own CA and all self-signed certs SSLContext sslcontext = SSLContexts.custom() .loadTrustMaterial(cert, keystore.toCharArray(), new TrustSelfSignedStrategy()).build(); // Allow TLSv1 protocol only SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" }, null, NoopHostnameVerifier.INSTANCE); httpClient = HttpClients.custom().setSSLSocketFactory(sslsf).build(); } else { httpClient = HttpClients.createDefault(); } ResponseHandler<String> responseHandler = new BasicResponseHandler(); try (CloseableHttpClient _httpClient = httpClient; CloseableHttpResponse res = _httpClient.execute(httppost);) { StringEntity requestEntity = new StringEntity(json, "utf-8"); requestEntity.setContentEncoding("UTF-8"); httppost.setHeader("Content-type", "application/json"); httppost.setEntity(requestEntity); // 傳送HttpPost請求,獲取返回值 returnValue = httpClient.execute(httppost, responseHandler); // 調介面獲取返回值,用此方法 // System.out.println(returnValue); } return returnValue; } }