HttpClient4.5 post请求xml到服务器
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;
- }
- <span style="white-space:pre;"> </span>
- /**
- * 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"); //<span style="color:rgb(85,85,85);font-family:'宋体', 'Arial Narrow', arial, serif;font-size:14px;">不指定参数名的方式来POST数据</span>
- 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>")); //<span style="color:rgb(85,85,85);font-family:'宋体', 'Arial Narrow', arial, serif;font-size:14px;">指定参数名的方式来POST数据</span>
- UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, "UTF-8");
- String responseContent = HttpsUtils.post(url, null, null, entity);
- System.out.println(responseContent);
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
HttpClient4.5 post请求xml到服务器的更多相关文章
- js进阶ajax基本用法(创建对象,连接服务器,发送请求,获取服务器传过来的数据)
js进阶ajax基本用法(创建对象,连接服务器,发送请求,获取服务器传过来的数据) 一.总结 1.ajax的浏览器的window对象的XMLHtmlRequest对象的两个重要方法:open(),se ...
- WebRequest请求错误(服务器提交了协议冲突. Section=ResponseHeader Detail=CR 后面必须是 LF)
WebRequest请求错误(服务器提交了协议冲突. Section=ResponseHeader Detail=CR 后面必须是 LF)解决办法,天津config文件,增加一个配置如下 <?x ...
- Fiddler 使用fiddler发送捕获的请求及模拟服务器返回
使用fiddler发送捕获的请求及模拟服务器返回 by:授客 QQ:1033553122 1.做好相关监听及代理设置 略 2.发送捕获的请求 如图 3.模拟服务器返回 本例的一个目的是,根据服务器返回 ...
- Ant运行build.xml执行服务器scp,异常解决jsch.jar
公司ant打包上线 一直出现这个问题. Ant运行build.xml执行服务器scp,异常解决jsch.jar BUILD FAILEDD:\eclipse\eclipse-jee-luna-SR2- ...
- 如何利用fiddler篡改发送请求和截取服务器信息
一.断点的两种方式 1.before response:在request请求未到达服务器之前打断 2.after response:在服务器响应之后打断 二.全局打断 1.全局打断就是中断fiddle ...
- 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 ...
- http400错误基本都是http请求参数与服务器接收参数不匹配
http400错误基本都是http请求参数与服务器接收参数不匹配造成的, 如:1)post请求,你发了个get请求 2)content-type指定不匹配致使参数无法读出来
- C/C++使用libcurl库发送http请求(get和post可以用于请求html信息,也可以请求xml和json等串)
C++要实现http网络连接,需要借助第三方库,libcurl使用起来还是很方便的 环境:win32 + vs2015 如果要在Linux下使用,基本同理 1,下载编译libcurl 下载curl源码 ...
- flask 设置https请求 访问flask服务器
学习过程中想要学教程中一样,做个假的微信公众号推送,不过去了微信开发文档怎么一直说需要https的请求(教学中没有说需要https,一直是http) 但是我的服务器只能使用http请求访问,如果硬是要 ...
随机推荐
- LINQ学习系列-----1.4 匿名对象
本篇内容接着上一篇继续讲述,本篇简单讲解匿名对象 一.匿名对象介绍 上代码: var result=new { ID=, Name="张三", Age= ...
- 【原创】python爬虫获取网站数据并存入本地数据库
#coding=utf-8 import urllib import re import MySQLdb dbnumber = MySQLdb.connect('localhost', 'root', ...
- 【转】Nginx反向代理和负载均衡
原文链接:http://www.cnblogs.com/shuoer/p/7820899.html Nginx反向代理和负载均衡 环境说明 由于我使用的是windows系统,所以我用虚拟机虚拟出来了3 ...
- 【微服务】之四:轻松搞定SpringCloud微服务-负载均衡Ribbon
对于任何一个高可用高负载的系统来说,负载均衡是一个必不可少的名称.在大型分布式计算体系中,某个服务在单例的情况下,很难应对各种突发情况.因此,负载均衡是为了让系统在性能出现瓶颈或者其中一些出现状态下可 ...
- ThinkPHP5.0 实现 app支付宝支付功能
前几天做项目,要求要用到支付宝接口,第一次做,弄了好几天 各种坑啊,简单写一下我做支付宝支付的过程,希望对也是第一次做支付宝支付的童鞋有帮助, 不懂的可以先去支付平台看一下支付宝支付的文档,我是下的d ...
- Nodejs的运行原理-科普篇
前言 Nodejs目前处境稍显尴尬,很多语言都已经拥有异步非阻塞的能力.阿里的思路是比较合适的,但是必须要注意,绝对不能让node做太多的业务逻辑,他只适合接收生成好的数据,然后或渲染后,或直接发送到 ...
- 解决zabbix中文显示乱码问题
中文显示问题,图表乱码 解决办法: [root@zabbix ~]# cd /usr/share/zabbix/include/ [root@zabbix include]# vim locales. ...
- win10 mysql详尽安装教程
我的电脑系统是win10 64位系统 我安装mysql不下5次,装好了又卸,卸了又装,看了老多篇文章和博客,非常感谢博主的无私帮助,以下是这些博主的文章: https://www.cnblogs.co ...
- Qwtpolar的编译
Qwtpolar是Qt的一个第三方扩展,用于绘制极坐标下的函数图形.官方网站在: http://sourceforge.net/projects/qwtpolar/ 新版的QGIS2.8依赖这个库,所 ...
- node-koa搭建MVC/RESTful API项目
本文将介绍如何基于node-koa搭建一个完整的mvc及restAPI的项目,项目封装了路由.模板引擎. 静态文件加载等基本功能:首先介绍项目的安装启动及目录结构说明,然后通过一个简单的登录页说明mv ...