java httpclient 返回xml_通过httpClient通过post向接口发送xml数据,并处理返回的xml报文...
//maven依赖
org.apache.httpcomponents
httpclient
4.5.6
importjava.io.IOException;importjava.net.URI;importjava.security.cert.CertificateException;importjava.security.cert.X509Certificate;importjava.util.ArrayList;importjava.util.HashMap;importjava.util.List;importjava.util.Map;//import org.apache.commons.collections.MapUtils;
importorg.apache.http.Consts;importorg.apache.http.HeaderIterator;importorg.apache.http.HttpEntity;importorg.apache.http.HttpResponse;importorg.apache.http.HttpStatus;importorg.apache.http.NameValuePair;importorg.apache.http.ParseException;importorg.apache.http.client.entity.UrlEncodedFormEntity;importorg.apache.http.client.methods.CloseableHttpResponse;importorg.apache.http.client.methods.HttpGet;importorg.apache.http.client.methods.HttpPost;importorg.apache.http.client.utils.URIBuilder;importorg.apache.http.config.Registry;importorg.apache.http.config.RegistryBuilder;importorg.apache.http.conn.socket.ConnectionSocketFactory;importorg.apache.http.conn.socket.PlainConnectionSocketFactory;importorg.apache.http.conn.ssl.NoopHostnameVerifier;importorg.apache.http.conn.ssl.SSLConnectionSocketFactory;importorg.apache.http.conn.ssl.TrustStrategy;importorg.apache.http.entity.ContentType;importorg.apache.http.entity.StringEntity;importorg.apache.http.impl.client.CloseableHttpClient;importorg.apache.http.impl.client.HttpClients;importorg.apache.http.impl.conn.PoolingHttpClientConnectionManager;importorg.apache.http.message.BasicNameValuePair;importorg.apache.http.ssl.SSLContextBuilder;importorg.apache.http.util.EntityUtils;/***
* @ClassName: HttpsUtils
* @Description: TODO(https post忽略证书请求)*/
public classHttpClientUtils {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= newSSLContextBuilder();//全部信任 不做身份鉴定
builder.loadTrustMaterial(null, newTrustStrategy() {
@Overridepublic boolean isTrusted(X509Certificate[] x509Certificates, String s) throwsCertificateException {return true;
}
});
sslsf= newSSLConnectionSocketFactory(builder.build(),new String[]{"SSLv2Hello", "SSLv3", "TLSv1", "TLSv1.2"}, null, NoopHostnameVerifier.INSTANCE);
Registry registry = RegistryBuilder.create()
.register(HTTP,newPlainConnectionSocketFactory()).register(HTTPS, sslsf).build();
cm= newPoolingHttpClientConnectionManager(registry);
cm.setMaxTotal(200);//max connection
} catch(Exception e) {
e.printStackTrace();
}
}//public static String post(String url, Map header, Map 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 entry : header.entrySet()) {//httpPost.addHeader(entry.getKey(), entry.getValue());//}//}// //设置请求参数//if (MapUtils.isNotEmpty(param)) {//List formparams = new ArrayList();//for (Map.Entry 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;//}
public staticString postXML(String url,String xml){
CloseableHttpClient client= null;
CloseableHttpResponse resp= null;try{
HttpPost httpPost= newHttpPost(url);
httpPost.setHeader("Content-Type", "text/xml; charset=UTF-8");
client=HttpClients.createDefault();
StringEntity entityParams= new StringEntity(xml,"utf-8");
httpPost.setEntity(entityParams);
client=HttpClients.createDefault();
resp=client.execute(httpPost);
String resultMsg= EntityUtils.toString(resp.getEntity(),"utf-8");returnresultMsg;
}catch(Exception e){
e.printStackTrace();
}finally{try{if(client!=null){
client.close();
}if(resp != null){
resp.close();
}
}catch(IOException e) {
e.printStackTrace();
}
}return null;
}public static CloseableHttpClient getHttpClient() throwsException {
CloseableHttpClient httpClient=HttpClients.custom().setSSLSocketFactory(sslsf).setConnectionManager(cm)
.setConnectionManagerShared(true).build();returnhttpClient;
}public static String readHttpResponse(HttpResponse httpResponse) throwsParseException, IOException {
StringBuilder builder= newStringBuilder();//获取响应消息实体
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", ""));
}returnbuilder.toString();
}/*** get发送数据
*@paramurl
*@paramparam
*@return
*/
public static String doGet(String url, Mapparam) {//创建Httpclient对象
CloseableHttpClient httpclient =HttpClients.createDefault();
String resultString= "";
CloseableHttpResponse response= null;try{//创建uri
URIBuilder builder = newURIBuilder(url);if (param != null) {for(String key : param.keySet()) {
builder.addParameter(key, param.get(key));
}
}
URI uri=builder.build();//创建http GET请求
HttpGet httpGet = newHttpGet(uri);//执行请求
response =httpclient.execute(httpGet);//判断返回状态是否为200
if (response.getStatusLine().getStatusCode() == 200) {
resultString= EntityUtils.toString(response.getEntity(), "UTF-8");
}
}catch(Exception e) {
e.printStackTrace();
}finally{try{if (response != null) {
response.close();
}
httpclient.close();
}catch(IOException e) {
e.printStackTrace();
}
}returnresultString;
}/*** get发送数据
*@paramurl
*@return
*/
public staticString doGet(String url) {return doGet(url, null);
}/*** post发送数据
*@paramurl
*@paramparam
*@return
*/
public static String doPost(String url, Mapparam) {//创建Httpclient对象
CloseableHttpClient httpClient =HttpClients.createDefault();
CloseableHttpResponse response= null;
String resultString= "";try{//创建Http Post请求
HttpPost httpPost = newHttpPost(url);//创建参数列表
if (param != null) {
List paramList = new ArrayList<>();for(String key : param.keySet()) {
paramList.add(newBasicNameValuePair(key, param.get(key)));
}//模拟表单
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList,"utf-8");
httpPost.setEntity(entity);
}//执行http请求
response =httpClient.execute(httpPost);
resultString= EntityUtils.toString(response.getEntity(), "utf-8");
}catch(Exception e) {
e.printStackTrace();
}finally{try{
response.close();
}catch(IOException e) {//TODO Auto-generated catch block
e.printStackTrace();
}
}returnresultString;
}/*** post发送数据
*@paramurl
*@return
*/
public staticString doPost(String url) {return doPost(url, null);
}/*** post发送json形式的数据
*@paramurl
*@paramjson
*@return
*/
public staticString doPostJson(String url, String json) {//创建Httpclient对象
CloseableHttpClient httpClient =HttpClients.createDefault();
CloseableHttpResponse response= null;
String resultString= "";try{//创建Http Post请求
HttpPost httpPost = newHttpPost(url);//创建请求内容
StringEntity entity = newStringEntity(json, ContentType.APPLICATION_JSON);
httpPost.setEntity(entity);//执行http请求
response =httpClient.execute(httpPost);
resultString= EntityUtils.toString(response.getEntity(), "utf-8");
}catch(Exception e) {
e.printStackTrace();
}finally{try{
response.close();
}catch(IOException e) {//TODO Auto-generated catch block
e.printStackTrace();
}
}returnresultString;
}
}
java httpclient 返回xml_通过httpClient通过post向接口发送xml数据,并处理返回的xml报文...相关推荐
- java实现socket连接,向指定主机指定端口发送socket数据,并获取响应数据
全栈工程师开发手册 (作者:栾鹏) java教程全解 java实现socket连接,向指定主机指定端口发送socket数据,并获取响应数据 测试代码 public static void main(S ...
- java解析通讯录xml_企业微信通讯录回调 成员回调 (新增成员和编辑成员)xml解析错误...
提问前,请确保阅读过项目首页说明以及wiki开发文档相关内容,尤其是常见问题部分.完成内容后,请务必移除包括本句在内的无用内容,以免影响阅读,否则直接关闭,谢谢合作~ 另外如果确认属于bug,而且已明 ...
- python map函数返回类型_使用map和lambda函数发送两个参数并返回两个值
因为您说您只需要一个模型,而不是每个值都需要一个新模型,所以这相当简单.更改:hnd = map(lambda (valua): function_f(valua), list_value) 致:mo ...
- Postman测试工具调试接口详细教程【向后端发送Json数据并接收返回的Json结果】
Postman测试工具调试接口详细教程 前些天发现了一个巨牛的人工智能学习网站,通俗易懂,风趣幽默,忍不住分享一下给大家.跳转网站:人工智能学习网站 简介 Postman,中文译为邮递员,邮差 Pos ...
- xml文件解析 (DOM4J解析XML) -java
文章目录 前言 一.本地XML解析 1.导包并配置 1.在项目下新建lib文件夹,并把jar包导入. 2.更改项目配置 2.编写一个简单的本地XML文件 3.解析本地XML文件: 二.解析网络上的XM ...
- JAVA网络爬爬学习之HttpClient+Jsoup
JAVA网络爬爬学习 HttpClient用法简单整理 GET请求 无参 带参 POST请求 无参 带参 连接池 请求request的相关配置 httpclient用法详解 Jsoup用法简单整理 j ...
- Java爬虫(二)-- httpClient模拟Http请求+jsoup页面解析
博客 学院 下载 GitChat TinyMind 论坛 APP 问答 商城 VIP会员 活动 招聘 ITeye 写博客 发Chat 传资源 登录注册 原 Java爬虫(二)-- httpClient ...
- httpclient妙用一 httpclient作为客户端调用soap webservice(转)
前面有一篇使用HttpClient调用带参数的post接口方法,这里找到一篇使用HttpClient调用Soap协议接口的方式. 原文地址:httpclient妙用一 httpclient作为客户端调 ...
- java json转xml_关于JSON与XML的区别比较
现在互联网上,最流行的两大传输数据的标准就是json和XML了,关于谁是最好的,一直以来都是人们争论的话题,其实各有各的缺点和优点: 1.定义介绍 (1).XML定义 扩展标记语言 (Extensib ...
最新文章
- 14 款命令行常用工具的替代品!
- Jpcap过滤GTunnel程序数据包
- 信息系统项目管理师论文:论项目的风险管理
- yum 卸载_不小心把Centos的yum给卸载了怎么办
- pyqt5实现注册界面并获得文本框内容
- 前端学习(1247):购物车1
- tar linux 举例,linux 的tar 命令详解举例
- 庆功会(信息学奥数一本通-T1269)
- leetcode题解200-岛屿数量
- 谨防 ActiveSupport::Cache::Store 缓存 nil 值
- R 学习笔记《十二》 R语言初学者指南--格包
- SecureCRT资源下载安装
- 常见开源Java论坛(附JForum论坛安装以及部署)
- php后缀加swp,当编辑文件出现swp的时候如何处理
- 我是斗图王之python爬取表情包
- H3C交换机基础查询命令
- 基于微信小程序的毕业设计题目(20)php校园二手交易小程序(含开题报告、任务书、中期报告、答辩PPT、论文模板)
- CRMEB去除版权信息教程
- cmake:通过CMAKE_CXX_COMPILE_FEATURES判断编译器是否支持C++11
- influx客户端基本操作
热门文章
- python字符串的美化_shell 下使用python 美化输出json
- VUE的导入(HelloWord)
- Video和Audio标签的使用
- 日平均血糖与糖化血红蛋白对照关系
- 超级硬盘数据恢复软件v2.7.2.6_电脑磁盘上的视频误删如何恢复?误删视频恢复教程...
- mysql5.6+master+date_MySQL5.6的4个自带库详解
- ac86u原厂固件去广告_苹果发布最新固件IOS12.3.2,估计不修正你的手机
- anaconda中安装xgboost_在windows64位Anaconda3环境下安装XGBoost
- Ceph (2) - 安装Ceph集群方法 2:使用cephadm配置Nautilus版Ceph集群
- Newtonsoft 六个超简单又实用的特性,值得一试 【上篇】