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

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. @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. }

HttpClient4.5 post请求xml到服务器的更多相关文章

  1. js进阶ajax基本用法(创建对象,连接服务器,发送请求,获取服务器传过来的数据)

    js进阶ajax基本用法(创建对象,连接服务器,发送请求,获取服务器传过来的数据) 一.总结 1.ajax的浏览器的window对象的XMLHtmlRequest对象的两个重要方法:open(),se ...

  2. WebRequest请求错误(服务器提交了协议冲突. Section=ResponseHeader Detail=CR 后面必须是 LF)

    WebRequest请求错误(服务器提交了协议冲突. Section=ResponseHeader Detail=CR 后面必须是 LF)解决办法,天津config文件,增加一个配置如下 <?x ...

  3. Fiddler 使用fiddler发送捕获的请求及模拟服务器返回

    使用fiddler发送捕获的请求及模拟服务器返回 by:授客 QQ:1033553122 1.做好相关监听及代理设置 略 2.发送捕获的请求 如图 3.模拟服务器返回 本例的一个目的是,根据服务器返回 ...

  4. Ant运行build.xml执行服务器scp,异常解决jsch.jar

    公司ant打包上线 一直出现这个问题. Ant运行build.xml执行服务器scp,异常解决jsch.jar BUILD FAILEDD:\eclipse\eclipse-jee-luna-SR2- ...

  5. 如何利用fiddler篡改发送请求和截取服务器信息

    一.断点的两种方式 1.before response:在request请求未到达服务器之前打断 2.after response:在服务器响应之后打断 二.全局打断 1.全局打断就是中断fiddle ...

  6. js_html_input中autocomplete="off"在chrom中失效的解决办法 使用JS模拟锚点跳转 js如何获取url参数 C#模拟httpwebrequest请求_向服务器模拟cookie发送 实习期学到的技术(一) LinqPad的变量比较功能 ASP.NET EF 使用LinqPad 快速学习Linq

    js_html_input中autocomplete="off"在chrom中失效的解决办法 分享网上的2种办法: 1-可以在不需要默认填写的input框中设置 autocompl ...

  7. http400错误基本都是http请求参数与服务器接收参数不匹配

    http400错误基本都是http请求参数与服务器接收参数不匹配造成的, 如:1)post请求,你发了个get请求 2)content-type指定不匹配致使参数无法读出来

  8. C/C++使用libcurl库发送http请求(get和post可以用于请求html信息,也可以请求xml和json等串)

    C++要实现http网络连接,需要借助第三方库,libcurl使用起来还是很方便的 环境:win32 + vs2015 如果要在Linux下使用,基本同理 1,下载编译libcurl 下载curl源码 ...

  9. flask 设置https请求 访问flask服务器

    学习过程中想要学教程中一样,做个假的微信公众号推送,不过去了微信开发文档怎么一直说需要https的请求(教学中没有说需要https,一直是http) 但是我的服务器只能使用http请求访问,如果硬是要 ...

随机推荐

  1. python学习笔记 map&&reduce

    ---恢复内容开始--- 1.map 1)map其实相当对吧运算符进行一个抽象,返回的是一个对象,但是这里不知道为什么不可以对一个map返回变量打印两次,难道是因为回收了? def f(x): ret ...

  2. java 之 建造者模式(大话设计模式)

    建造者模式,在笔者看来比较试用于,定制一个业务流程,而流程的细节又不尽相同,每个细节又必不可少,这时应考虑使用建造者模式. 大话设计模式-类图 先看下笔者写的一个简单的例子. /** * 所有建造过程 ...

  3. web管理kvm ,安装webvirtmgr

    原创博文安装配置KVM http://www.cnblogs.com/elvi/p/7718574.htmlweb管理kvm http://www.cnblogs.com/elvi/p/7718582 ...

  4. KVM克隆 快照

    原创博文安装配置KVM http://www.cnblogs.com/elvi/p/7718574.htmlweb管理kvm http://www.cnblogs.com/elvi/p/7718582 ...

  5. linux上mysql安装与卸载

    以下步骤运行环境是centos6.5   1.查找以前是否装有mysql命令:rpm -qa|grep -i mysql2.删除mysql删除命令:rpm -e --nodeps 包名3.删除老版本m ...

  6. mysql 存储过程 小实例

    咱们先建个表吧 [SQL] 纯文本查看 复制代码 ? 1 2 3 4 5 6     CREATE TABLE `test1` (   `id` int(10) unsigned NOT NULL A ...

  7. 第三方登录,一般都是遵循OAuth2.0协议。

    1. QQ登录OAuth2.0协议开发流程 1.1 开发流程 申请接入,获取appid和appkey; 开发应用,设置协作者账号,上线之前只有协作者才能进行第三方登录 放置QQ登录按钮(这个自己可以用 ...

  8. slurm任务调度系统部署和测试(一)

    1.概述 本博客通过VMware workstation创建了虚拟机console,然后在console内部创建了8台kvm虚拟机,使用这8台虚拟机作为集群,来部署配置和测试slurm任务调度系统. ...

  9. Jarvis OJ - [XMAN]level0 - Writeup

    差不多最简单的pwn了吧,不过本菜鸟还是要发出来镇楼 分析一下,checksec 查看程序的各种保护机制 没有金丝雀,没有pie 执行时输出Hello,World,在进行输入,溢出嘛  开工 丢到id ...

  10. ElasticSearch 学习记录之集群分片内部原理

    分片内部原理 分片是如何工作的 为什么ES搜索是近实时性的 为什么CRUD 操作也是实时性 ES 是怎么保证更新被持久化时断电也不丢失数据 为什么删除文档不会立即释放空间 refresh, flush ...