HttpClient4.5 post请求xml到服务器

1.加入HttpClient4.5和junit依赖包

  1. <dependencies>  
  2.         <dependency>  
  3.             <groupId>org.apache.httpcomponents</groupId>  
  4.             <artifactId>httpclient</artifactId>  
  5.             <version>4.5</version>  
  6.         </dependency>  
  7.         <dependency>  
  8.             <groupId>commons-collections</groupId>  
  9.             <artifactId>commons-collections</artifactId>  
  10.             <version>3.2.2</version>  
  11.         </dependency>  
  12.         <dependency>  
  13.             <groupId>junit</groupId>  
  14.             <artifactId>junit</artifactId>  
  15.             <version>4.12</version>  
  16.         </dependency>  
  17.     </dependencies>  



2.编写工具类

  1. import java.io.IOException;  
  2. import java.security.cert.CertificateException;  
  3. import java.security.cert.X509Certificate;  
  4. import java.util.ArrayList;  
  5. import java.util.List;  
  6. import java.util.Map;  
  7.   
  8. import org.apache.commons.collections.MapUtils;  
  9. import org.apache.http.Consts;  
  10. import org.apache.http.HeaderIterator;  
  11. import org.apache.http.HttpEntity;  
  12. import org.apache.http.HttpResponse;  
  13. import org.apache.http.HttpStatus;  
  14. import org.apache.http.NameValuePair;  
  15. import org.apache.http.ParseException;  
  16. import org.apache.http.client.entity.UrlEncodedFormEntity;  
  17. import org.apache.http.client.methods.HttpPost;  
  18. import org.apache.http.config.Registry;  
  19. import org.apache.http.config.RegistryBuilder;  
  20. import org.apache.http.conn.socket.ConnectionSocketFactory;  
  21. import org.apache.http.conn.socket.PlainConnectionSocketFactory;  
  22. import org.apache.http.conn.ssl.NoopHostnameVerifier;  
  23. import org.apache.http.conn.ssl.SSLConnectionSocketFactory;  
  24. import org.apache.http.conn.ssl.TrustStrategy;  
  25. import org.apache.http.entity.StringEntity;  
  26. import org.apache.http.impl.client.CloseableHttpClient;  
  27. import org.apache.http.impl.client.HttpClients;  
  28. import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;  
  29. import org.apache.http.message.BasicNameValuePair;  
  30. import org.apache.http.ssl.SSLContextBuilder;  
  31. import org.apache.http.util.EntityUtils;  
  32.   
  33. /** 
  34.  *  
  35.     * @ClassName: HttpsUtils 
  36.     * @Description: TODO(https post忽略证书请求) 
  37.  */  
  38. public class HttpsUtils {  
  39.     private static final String HTTP = "http";  
  40.     private static final String HTTPS = "https";  
  41.     private static SSLConnectionSocketFactory sslsf = null;  
  42.     private static PoolingHttpClientConnectionManager cm = null;  
  43.     private static SSLContextBuilder builder = null;  
  44.     static {  
  45.         try {  
  46.             builder = new SSLContextBuilder();  
  47.             // 全部信任 不做身份鉴定  
  48.             builder.loadTrustMaterial(null, new TrustStrategy() {  
  49.                 @Override  
  50.                 public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {  
  51.                     return true;  
  52.                 }  
  53.             });  
  54.             sslsf = new SSLConnectionSocketFactory(builder.build(),  
  55.                     new String[] { "SSLv2Hello", "SSLv3", "TLSv1", "TLSv1.2" }, null, NoopHostnameVerifier.INSTANCE);  
  56.             Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory> create()  
  57.                     .register(HTTP, new PlainConnectionSocketFactory()).register(HTTPS, sslsf).build();  
  58.             cm = new PoolingHttpClientConnectionManager(registry);  
  59.             cm.setMaxTotal(200);// max connection  
  60.         } catch (Exception e) {  
  61.             e.printStackTrace();  
  62.         }  
  63.     }  
  64.   
  65.     /** 
  66.      * httpClient post请求 
  67.      *  
  68.      * @param url 
  69.      *            请求url 
  70.      * @param header 
  71.      *            头部信息 
  72.      * @param param 
  73.      *            请求参数 form提交适用 
  74.      * @param entity 
  75.      *            请求实体 json/xml提交适用 
  76.      * @return 可能为空 需要处理 
  77.      * @throws Exception 
  78.      * 
  79.      */  
  80.     public static String post(String url, Map<String, String> header, Map<String, String> param, StringEntity entity)  
  81.             throws Exception {  
  82.         String result = "";  
  83.         CloseableHttpClient httpClient = null;  
  84.         try {  
  85.             httpClient = getHttpClient();  
  86.             //HttpGet httpPost = new HttpGet(url);//get请求  
  87.             HttpPost httpPost = new HttpPost(url);//Post请求  
  88.             // 设置头信息  
  89.             if (MapUtils.isNotEmpty(header)) {  
  90.                 for (Map.Entry<String, String> entry : header.entrySet()) {  
  91.                     httpPost.addHeader(entry.getKey(), entry.getValue());  
  92.                 }  
  93.             }  
  94.             // 设置请求参数  
  95.             if (MapUtils.isNotEmpty(param)) {  
  96.                 List<NameValuePair> formparams = new ArrayList<NameValuePair>();  
  97.                 for (Map.Entry<String, String> entry : param.entrySet()) {  
  98.                     // 给参数赋值  
  99.                     formparams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));  
  100.                 }  
  101.                 UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(formparams, Consts.UTF_8);  
  102.                 httpPost.setEntity(urlEncodedFormEntity);  
  103.             }  
  104.             // 设置实体 优先级高  
  105.             if (entity != null) {  
  106.                 httpPost.addHeader("Content-Type", "text/xml");   
  107.                 httpPost.setEntity(entity);  
  108.             }  
  109.             HttpResponse httpResponse = httpClient.execute(httpPost);  
  110.             int statusCode = httpResponse.getStatusLine().getStatusCode();  
  111.             System.out.println("状态码:"+statusCode);  
  112.             if (statusCode == HttpStatus.SC_OK) {  
  113.                 HttpEntity resEntity = httpResponse.getEntity();  
  114.                 result = EntityUtils.toString(resEntity);  
  115.             } else {  
  116.                 readHttpResponse(httpResponse);  
  117.             }  
  118.         } catch (Exception e) {  
  119.             throw e;  
  120.         } finally {  
  121.             if (httpClient != null) {  
  122.                 httpClient.close();  
  123.             }  
  124.         }  
  125.         return result;  
  126.     }  
  1. <span style="white-space:pre;"> </span>  
  1. /** 
  2.      * httpClient post请求 
  3.      *  
  4.      * @param url 
  5.      *            请求url 
  6.      * @param header 
  7.      *            头部信息 
  8.      * @param param 
  9.      *            请求参数 form提交适用 
  10.      * @param entity 
  11.      *            请求实体 json/xml提交适用 (指定参数名的方式来POST数据) 
  12.      * @return 可能为空 需要处理 
  13.      * @throws Exception 
  14.      * 
  15.      */  
  16.     public static String post(String url, Map<String, String> header, Map<String, String> param, HttpEntity entity)  
  17.             throws Exception {  
  18.         String result = "";  
  19.         CloseableHttpClient httpClient = null;  
  20.         try {  
  21.             httpClient = getHttpClient();  
  22.             //HttpGet httpPost = new HttpGet(url);//get请求  
  23.             HttpPost httpPost = new HttpPost(url);//Post请求  
  24.             // 设置头信息  
  25.             if (MapUtils.isNotEmpty(header)) {  
  26.                 for (Map.Entry<String, String> entry : header.entrySet()) {  
  27.                     httpPost.addHeader(entry.getKey(), entry.getValue());  
  28.                 }  
  29.             }  
  30.             // 设置请求参数  
  31.             if (MapUtils.isNotEmpty(param)) {  
  32.                 List<NameValuePair> formparams = new ArrayList<NameValuePair>();  
  33.                 for (Map.Entry<String, String> entry : param.entrySet()) {  
  34.                     // 给参数赋值  
  35.                     formparams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));  
  36.                 }  
  37.                 UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(formparams, Consts.UTF_8);  
  38.                 httpPost.setEntity(urlEncodedFormEntity);  
  39.             }  
  40.             // 设置实体 优先级高  
  41.             if (entity != null) {  
  42.                 httpPost.setEntity(entity);  
  43.             }  
  44.             HttpResponse httpResponse = httpClient.execute(httpPost);  
  45.             int statusCode = httpResponse.getStatusLine().getStatusCode();  
  46.             System.out.println("状态码:"+statusCode);  
  47.             if (statusCode == HttpStatus.SC_OK) {  
  48.                 HttpEntity resEntity = httpResponse.getEntity();  
  49.                 result = EntityUtils.toString(resEntity);  
  50.             } else {  
  51.                 readHttpResponse(httpResponse);  
  52.             }  
  53.         } catch (Exception e) {  
  54.             throw e;  
  55.         } finally {  
  56.             if (httpClient != null) {  
  57.                 httpClient.close();  
  58.             }  
  59.         }  
  60.         return result;  
  61.     }  
  1.     public static CloseableHttpClient getHttpClient() throws Exception {  
  2.         CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(sslsf).setConnectionManager(cm)  
  3.                 .setConnectionManagerShared(true).build();  
  4.         return httpClient;  
  5.     }  
  6.   
  7.     public static String readHttpResponse(HttpResponse httpResponse) throws ParseException, IOException {  
  8.         StringBuilder builder = new StringBuilder();  
  9.         // 获取响应消息实体  
  10.         HttpEntity entity = httpResponse.getEntity();  
  11.         // 响应状态  
  12.         builder.append("status:" + httpResponse.getStatusLine());  
  13.         builder.append("headers:");  
  14.         HeaderIterator iterator = httpResponse.headerIterator();  
  15.         while (iterator.hasNext()) {  
  16.             builder.append(" " + iterator.next());  
  17.         }  
  18.         // 判断响应实体是否为空  
  19.         if (entity != null) {  
  20.             String responseString = EntityUtils.toString(entity);  
  21.             builder.append("response length:" + responseString.length());  
  22.             builder.append("response content:" + responseString.replace(" ", ""));  
  23.         }  
  24.         return builder.toString();  
  25.     }  
  26. }  

3.测试类

  1. @Test  
  2.     public void testSendHttpPost2() {  
  3.         String url = "https://XXXX.XXX.XXX.XXX/XXX/XXX.html";  
  4.         try {  
  5.             StringEntity entity = new StringEntity(getXMLString(), "UTF-8"); //<span style="color:rgb(85,85,85);font-family:'宋体', 'Arial Narrow', arial, serif;font-size:14px;">不指定参数名的方式来POST数据</span>  
  6.             String responseContent = HttpsUtils.post(url, null, null, entity);  
  7.             System.out.println(responseContent);  
  8.         } catch (Exception e) {  
  9.             e.printStackTrace();  
  10.         }  
  11.     }  
  1.   
    1. @Test  
    2.     public void testSendHttpPost3() {//https://209.160.54.4/suns/XML_Rx.php  
    3.         String url = "http://10.122.1.92:8080/products.html";  
    4.         try {  
    5.             List<NameValuePair> formparams = new ArrayList<NameValuePair>();   
    6.             formparams.add(new BasicNameValuePair("xmldate", "<html>你好啊啊</html>")); //<span style="color:rgb(85,85,85);font-family:'宋体', 'Arial Narrow', arial, serif;font-size:14px;">指定参数名的方式来POST数据</span>  
    7.             UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, "UTF-8");   
    8.             String responseContent = HttpsUtils.post(url, null, null, entity);  
    9.             System.out.println(responseContent);  
    10.         } catch (Exception e) {  
    11.             e.printStackTrace();  
    12.         }  
    13.     } 
原文地址:https://www.cnblogs.com/lykbk/p/warewerrwer2435324233.html