1.加入HttpClient4.5和junit依賴包
<dependencies> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5</version> </dependency> <dependency> <groupId>commons-collections</groupId> <artifactId>commons-collections</artifactId> <version>3.2.2</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> </dependency> </dependencies>2.編寫工具類import java.io.IOException;import java.security.cert.CertificateException;import java.security.cert.X509Certificate;import java.util.ArrayList;import java.util.List;import java.util.Map;import org.apache.commons.collections.MapUtils;import org.apache.http.Consts;import org.apache.http.HeaderIterator;import org.apache.http.HttpEntity;import org.apache.http.HttPResponse;import org.apache.http.HttpStatus;import org.apache.http.NameValuePair;import org.apache.http.ParseException;import org.apache.http.client.entity.UrlEncodedFormEntity;import org.apache.http.client.methods.HttpPost;import org.apache.http.config.Registry;import org.apache.http.config.RegistryBuilder;import org.apache.http.conn.socket.ConnectionSocketFactory;import org.apache.http.conn.socket.PlainConnectionSocketFactory;import org.apache.http.conn.ssl.NoopHostnameVerifier;import org.apache.http.conn.ssl.SSLConnectionSocketFactory;import org.apache.http.conn.ssl.TrustStrategy;import org.apache.http.entity.StringEntity;import org.apache.http.impl.client.CloseableHttpClient;import org.apache.http.impl.client.HttpClients;import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;import org.apache.http.message.BasicNameValuePair;import org.apache.http.ssl.SSLContextBuilder;import org.apache.http.util.EntityUtils;/** * * @ClassName: HttpsUtils * @Description: TODO(https post忽略證書請求) */public class HttpsUtils { private static final String HTTP = "http"; private static final String HTTPS = "https"; private static SSLConnectionSocketFactory sslsf = null; private static PoolingHttpClientConnectionManager cm = null; private static SSLContextBuilder builder = null; static { try { builder = new SSLContextBuilder(); // 全部信任 不做身份鑒定 builder.loadTrustMaterial(null, new TrustStrategy() { @Override public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException { return true; } }); sslsf = new SSLConnectionSocketFactory(builder.build(), new String[] { "SSLv2Hello", "SSLv3", "TLSv1", "TLSv1.2" }, null, NoopHostnameVerifier.INSTANCE); Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory> create() .register(HTTP, new PlainConnectionSocketFactory()).register(HTTPS, sslsf).build(); cm = new PoolingHttpClientConnectionManager(registry); cm.setMaxTotal(200);// max connection } catch (Exception e) { e.printStackTrace(); } } /** * httpClient post請求 * * @param url * 請求url * @param header * 頭部信息 * @param param * 請求參數 form提交適用 * @param entity * 請求實體 json/xml提交適用 * @return 可能為空 需要處理 * @throws Exception * */ public static String post(String url, Map<String, String> header, Map<String, String> param, StringEntity entity) throws Exception { String result = ""; CloseableHttpClient httpClient = null; try { httpClient = getHttpClient(); //HttpGet httpPost = new HttpGet(url);//get請求 HttpPost httpPost = new HttpPost(url);//Post請求 // 設置頭信息 if (MapUtils.isNotEmpty(header)) { for (Map.Entry<String, String> entry : header.entrySet()) { httpPost.addHeader(entry.getKey(), entry.getValue()); } } // 設置請求參數 if (MapUtils.isNotEmpty(param)) { List<NameValuePair> formparams = new ArrayList<NameValuePair>(); for (Map.Entry<String, String> entry : param.entrySet()) { // 給參數賦值 formparams.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); } UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(formparams, Consts.UTF_8); httpPost.setEntity(urlEncodedFormEntity); } // 設置實體 優先級高 if (entity != null) { httpPost.addHeader("Content-Type", "text/xml"); httpPost.setEntity(entity); } HttpResponse httpResponse = httpClient.execute(httpPost); int statusCode = httpResponse.getStatusLine().getStatusCode(); System.out.println("狀態碼:"+statusCode); if (statusCode == HttpStatus.SC_OK) { HttpEntity resEntity = httpResponse.getEntity(); result = EntityUtils.toString(resEntity); } else { readHttpResponse(httpResponse); } } catch (Exception e) { throw e; } finally { if (httpClient != null) { httpClient.close(); } } return result; }/** * httpClient post請求 * * @param url * 請求url * @param header * 頭部信息 * @param param * 請求參數 form提交適用 * @param entity * 請求實體 json/xml提交適用 (指定參數名的方式來POST數據) * @return 可能為空 需要處理 * @throws Exception * */ public static String post(String url, Map<String, String> header, Map<String, String> param, HttpEntity entity) throws Exception { String result = ""; CloseableHttpClient httpClient = null; try { httpClient = getHttpClient(); //HttpGet httpPost = new HttpGet(url);//get請求 HttpPost httpPost = new HttpPost(url);//Post請求 // 設置頭信息 if (MapUtils.isNotEmpty(header)) { for (Map.Entry<String, String> entry : header.entrySet()) { httpPost.addHeader(entry.getKey(), entry.getValue()); } } // 設置請求參數 if (MapUtils.isNotEmpty(param)) { List<NameValuePair> formparams = new ArrayList<NameValuePair>(); for (Map.Entry<String, String> entry : param.entrySet()) { // 給參數賦值 formparams.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); } UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(formparams, Consts.UTF_8); httpPost.setEntity(urlEncodedFormEntity); } // 設置實體 優先級高 if (entity != null) { httpPost.setEntity(entity); } HttpResponse httpResponse = httpClient.execute(httpPost); int statusCode = httpResponse.getStatusLine().getStatusCode(); System.out.println("狀態碼:"+statusCode); if (statusCode == HttpStatus.SC_OK) { HttpEntity resEntity = httpResponse.getEntity(); result = EntityUtils.toString(resEntity); } else { readHttpResponse(httpResponse); } } catch (Exception e) { throw e; } finally { if (httpClient != null) { httpClient.close(); } } return result; }public static CloseableHttpClient getHttpClient() throws Exception { CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(sslsf).setConnectionManager(cm) .setConnectionManagerShared(true).build(); return httpClient; } public static String readHttpResponse(HttpResponse httpResponse) throws ParseException, IOException { StringBuilder builder = new StringBuilder(); // 獲取響應消息實體 HttpEntity entity = httpResponse.getEntity(); // 響應狀態 builder.append("status:" + httpResponse.getStatusLine()); builder.append("headers:"); HeaderIterator iterator = httpResponse.headerIterator(); while (iterator.hasNext()) { builder.append("/t" + iterator.next()); } // 判斷響應實體是否為空 if (entity != null) { String responseString = EntityUtils.toString(entity); builder.append("response length:" + responseString.length()); builder.append("response content:" + responseString.replace("/r/n", "")); } return builder.toString(); }}3.測試類@Test public void testSendHttpPost2() { String url = "https://XXXX.XXX.XXX.XXX/XXX/XXX.html"; try { StringEntity entity = new StringEntity(getXMLString(), "UTF-8"); //不指定參數名的方式來POST數據 String responseContent = HttpsUtils.post(url, null, null, entity); System.out.println(responseContent); } catch (Exception e) { e.printStackTrace(); } }@Test public void testSendHttpPost3() {//https://209.160.54.4/suns/XML_Rx.php String url = "http://10.122.1.92:8080/products.html"; try { List<NameValuePair> formparams = new ArrayList<NameValuePair>(); formparams.add(new BasicNameValuePair("xmldate", "<html>你好啊啊</html>")); //指定參數名的方式來POST數據 UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, "UTF-8"); String responseContent = HttpsUtils.post(url, null, null, entity); System.out.println(responseContent); } catch (Exception e) { e.printStackTrace(); } }
|
新聞熱點
疑難解答