发送xml格式的http请求工具类

发送xml格式的http请求

package com.yannis.utils;import com.google.gson.Gson;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.client.utils.HttpClientUtils;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;import java.io.IOException;
import java.lang.reflect.Type;
import java.util.List;
import java.util.Map;public class RestRpcClient {private static Log LOG = LogFactory.getLog(RestRpcClient.class);private String url;public RestRpcClient(String url) {this.url = url;}public String call(Map<String, String> paramMap) {try {HttpUriRequest request = buildUriRequest(url, paramMap);return HttpClients.createDefault().execute(request, new BasicResponseHandler());} catch (Exception e) {LOG.error("*** HttpClients execute failed due to [" + e.getMessage() + "], url: " + url, e);}return null;}public String call(List<NameValuePair> pares) {try {HttpPost httpPost = new HttpPost(url);httpPost.setEntity(new UrlEncodedFormEntity(pares, HTTP.UTF_8));return HttpClients.createDefault().execute(httpPost, new BasicResponseHandler());} catch (Exception e) {return throwSystemError(e, url);}}public <T> T call(Map<String, String> paramMap, Class<T> typeClass) {HttpResponse response = null;try {HttpUriRequest request = buildUriRequest(url, paramMap);response = HttpClients.createDefault().execute(request);return resolveRsp(typeClass, response);} catch (Exception e) {return throwSystemError(e, url);} finally {HttpClientUtils.closeQuietly(response);}}public static <T> T invokeXml(String url, Object rq, Class<T> typeClass) {HttpResponse response = null;try {HttpPost httpPost = new HttpPost(url);StringEntity entity = new StringEntity(JaxbMapper.toXml(rq), ContentType.create("application/xml", "UTF-8"));httpPost.setEntity(entity);//            HttpClient instance =
//                    HttpClientBuilder.create().setRedirectStrategy(new LaxRedirectStrategy()).build();response = HttpClients.createDefault().execute(httpPost);int statusCode = response.getStatusLine().getStatusCode();if(statusCode == HttpStatus.SC_MOVED_PERMANENTLY || statusCode == HttpStatus.SC_MOVED_TEMPORARILY){response = HttpClients.createDefault().execute(httpPost);}return resolveRspXml(typeClass, response);} catch (Exception e) {return throwSystemError(e, url);} finally {HttpClientUtils.closeQuietly(response);}}public static <T> T invokeXmlHtml(String url, Object rq, Class<T> typeClass) {HttpResponse response = null;try {HttpPost httpPost = new HttpPost(url);StringEntity entity = new StringEntity(JaxbMapper.toXml(rq), ContentType.create("application/xml", "UTF-8"));httpPost.setEntity(entity);//            HttpClient instance =
//                    HttpClientBuilder.create().setRedirectStrategy(new LaxRedirectStrategy()).build();response = HttpClients.createDefault().execute(httpPost);int statusCode = response.getStatusLine().getStatusCode();if(statusCode == HttpStatus.SC_MOVED_PERMANENTLY || statusCode == HttpStatus.SC_MOVED_TEMPORARILY){response = HttpClients.createDefault().execute(httpPost);}return resolveRspXmlHtml(typeClass, response);} catch (Exception e) {return throwSystemError(e, url);} finally {HttpClientUtils.closeQuietly(response);}}public static <T> T invoke(String url, Object rq, Class<T> typeClass) {HttpResponse response = null;try {HttpPost httpPost = new HttpPost(url);StringEntity entity = new StringEntity(new Gson().toJson(rq), ContentType.create("application/json", "UTF-8"));httpPost.setEntity(entity);response = HttpClients.createDefault().execute(httpPost);return resolveRsp(typeClass, response);} catch (Exception e) {return throwSystemError(e, url);} finally {HttpClientUtils.closeQuietly(response);}}private static <T> T resolveRsp(Class<T> typeClass, HttpResponse response) throws IOException {int statusCode = response.getStatusLine().getStatusCode();if (statusCode == HttpStatus.SC_OK) {return new Gson().fromJson(EntityUtils.toString(response.getEntity(), "UTF-8"), typeClass);} else {throw new RuntimeException("invalid status code: " + statusCode);}}private static <T> T resolveRspXml(Class<T> typeClass, HttpResponse response) throws Exception {int statusCode = response.getStatusLine().getStatusCode();if (statusCode == HttpStatus.SC_OK) {return JaxbMapper.fromXml(EntityUtils.toString(response.getEntity(), "UTF-8"), typeClass);} else {String strResponse = EntityUtils.toString(response.getEntity(), "UTF-8");try{return JaxbMapper.fromXml(strResponse, typeClass);}catch (Exception e){// 解析错误不影响主流程}LOG.error("invalid status code: " + statusCode +  " response:" + strResponse);throw new RuntimeException("invalid status code: " + statusCode +  ",response:" + strResponse);}}private static <T> T resolveRspXmlHtml(Class<T> typeClass, HttpResponse response) throws Exception {int statusCode = response.getStatusLine().getStatusCode();if (statusCode == HttpStatus.SC_OK) {String html = EntityUtils.toString(response.getEntity(), "UTF-8");return JaxbMapper.fromXml(StringEscapeUtils.unescapeHtml4(html), typeClass);} else {String html = EntityUtils.toString(response.getEntity(), "UTF-8");String strResponse = StringEscapeUtils.unescapeHtml4(html);try{return JaxbMapper.fromXml(strResponse, typeClass);}catch (Exception e){// 解析错误不影响主流程}LOG.error("invalid status code: " + statusCode +  " response:" + strResponse);throw new RuntimeException("invalid status code: " + statusCode +  ",response:" + strResponse);}}private static <T> T throwSystemError(Exception e, String url) {String error = "*** HttpClients execute failed due to [" + e.getMessage() + "], url: " + url;LOG.error(error, e);throw new RuntimeException(error);}@Deprecatedpublic <T> T call(Object rq, Class<T> typeClass) {HttpResponse response = null;try {HttpPost httpPost = new HttpPost(url);StringEntity entity = new StringEntity(new Gson().toJson(rq), ContentType.create("application/json", "UTF-8"));
//            entity.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));httpPost.setEntity(entity);response = HttpClients.createDefault().execute(httpPost);int statusCode = response.getStatusLine().getStatusCode();if (statusCode == HttpStatus.SC_OK) {T rs = new Gson().fromJson(EntityUtils.toString(response.getEntity(), "UTF-8"), typeClass);return rs;} else {throw new RuntimeException("invalid status code: " + statusCode);}} catch (Exception e) {return throwSystemError(e, url);} finally {HttpClientUtils.closeQuietly(response);}}private HttpUriRequest buildUriRequest(String url, Map<String, String> paramMap) {RequestBuilder requestBuilder = RequestBuilder.post().setUri(url);for (Map.Entry<String, String> e : paramMap.entrySet()) {requestBuilder.addParameter(e.getKey(), e.getValue());}return requestBuilder.build();}public static <T> T invoke(String url, Object rq, Type successType, Type failureType) {HttpResponse response = null;try {HttpPost httpPost = new HttpPost(url);StringEntity entity = new StringEntity(new Gson().toJson(rq), ContentType.create("application/json", "UTF-8"));httpPost.setEntity(entity);response = HttpClients.createDefault().execute(httpPost);int statusCode = response.getStatusLine().getStatusCode();if (statusCode == HttpStatus.SC_OK) {return resolveRsp(EntityUtils.toString(response.getEntity(), "UTF-8"), successType, failureType);} else {throw new RuntimeException("invalid status code: " + statusCode);}} catch (Exception e) {return throwSystemError(e, url);} finally {HttpClientUtils.closeQuietly(response);}}private static <T> T resolveRsp(String json, Type successType, Type failureType) throws IOException {if (json != null && json.contains("success\":true")) {return new Gson().fromJson(json, successType);} else {return new Gson().fromJson(json, failureType);}}
}

使用

 HotelRoomsResponse hotelRoomsResponse = RestRpcClient.invokeXml(jalanUrlProperties.getRooms(), hotelRoomsRequest, HotelRoomsResponse.class);

请求与响应对象要符合JAXB规范。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/195413.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

继续画图带你学习TCP 其他 7 大特性

四、滑动窗口机制 五、流量控制 六、拥塞控制 (安全机制) 七、延迟应答 (效率机制) 八、捎带应答 (效率机制) 九、粘包问题 十、保活机制 TCP总结 四、滑动窗口机制 滑动窗口机制&#xff0c;是在可靠性的前提下&#xff0c;进一步地提高传输效率 认识滑动窗口 一发一收…

vscode的eslint检查代码格式不严谨的快速修复

问题&#xff1a; 原因&#xff1a;复制的代码&#xff0c;esLint检查代码格式不正确。或者写的代码位置不严谨&#xff0c;总是提示 解决 设置在Ctrl S保存时自动格式化代码 1、vscode设置 2、点击右上角&#xff0c;切换json模式 3、添加设置 "editor.codeActionsOn…

JavaScript中使用JSON的基本操作示例

简介 JSON&#xff08;JavaScript Object Notation&#xff09;是一种数据交换格式&#xff0c;也是JavaScript中处理数据的常见方式之一。JSON是一种轻量级的数据交换格式&#xff0c;易于阅读和编写&#xff0c;同时也易于解析和生成。在JavaScript中&#xff0c;可以使用内…

Linux gdb调试(总结)

1 gdb的作用 gdb 是 GNU 发布的一个强大的程序调试工具,也是 Linux 程序员不可或缺的一大利器。 2 gdb的使用: (1) 调试讲解的代码 //---------addsub.h--------- #pragma once int jfx_addition (int* a, int* b); int jfx_subtraction (int* a, int* b);//---------adds…

Rust UI开发(五):iced中如何进行页面布局(pick_list的使用)?(串口调试助手)

注&#xff1a;此文适合于对rust有一些了解的朋友 iced是一个跨平台的GUI库&#xff0c;用于为rust语言程序构建UI界面。 这是一个系列博文&#xff0c;本文是第五篇&#xff0c;前四篇链接&#xff1a; 1、Rust UI开发&#xff08;一&#xff09;&#xff1a;使用iced构建UI时…

【零基础入门Python】Python If Else流程控制

✍面向读者&#xff1a;所有人 ✍所属专栏&#xff1a;零基础入门Pythonhttps://blog.csdn.net/arthas777/category_12455877.html Python if语句 Python if语句的流程图 Python if语句示例 Python If-Else Statement Python if else语句的流程图 使用Python if-else语句 …

JVM 运行时内存篇

面试题&#xff1a; 讲一下为什么JVM要分为堆、方法区等&#xff1f;原理是什么&#xff1f;&#xff08;UC、智联&#xff09; JVM的分区了解吗&#xff0c;内存溢出发生在哪个位置 &#xff08;亚信、BOSS&#xff09; 简述各个版本内存区域的变化&#xff1…

木质家具行业分析:我国市场规模总资产达1669.19亿元

木质家具是指以天然木材和木质人造板为主要材料&#xff0c;配以其他辅料(如油漆、贴面材料、玻璃、五金配件等)制作各种家具的生产活动。 近年来实木家具越来越受到广大消费者的青睐。继板式家具、板式定制家具之后&#xff0c;板木家具与整木定制家具渐渐走进人们的视野。但目…

酵母双杂交服务专题(四)

关于酵母双杂交服务的常见问题 问题1&#xff1a;酵母双杂交的筛选流程&#xff1f; 研究者将特定基因作为钓饵&#xff0c;在一个精心挑选的cDNA文库中进行筛选&#xff0c;目的是找到与该钓饵蛋白发生相互作用的蛋白质。通过这种筛选&#xff0c;可以从阳性反应的酵母菌株中…

python处理的例子

例子一&#xff08;咖啡列表的处理&#xff09; 把 coffee_list [ 32Latte, _Americano30,/34Cappuccino, Mocha35]输出为&#xff1a; 1 Latte 2 Americano 3 Cappuccino 4 Mocha def clean_list(lst):cleaned_list []for item in lst:for c in item:if c.isalpha() ! Tr…

Cesium 顶点吸附和区域拾取

Cesium 顶点吸附和区域拾取 基于深度实现可以自定义拾取范围大小 // 顶点吸附// const result pickAreaHelper.pickNearest(viewer.scene, movement.endPosition, 32, 32);// 区域拾取const result pickAreaHelper.pickArea(viewer.scene, movement.endPosition, 32, 32);顶…

新生儿规避感染的完全指南

引言&#xff1a; 新生儿的免疫系统尚处于发育阶段&#xff0c;对外界环境的抵抗力相对较弱。因此&#xff0c;规避感染成为父母在新生儿护理中至关重要的一环。本文将深入探讨新生儿规避感染的注意事项&#xff0c;为父母提供详尽的指南&#xff0c;以确保宝宝健康成长。 第一…

树莓派Python程序开机自启动(Linux下Python程序开机自启动)

前一阵子用python编写了一个驱动I2C程序读写屏幕&#xff0c;输出IP的小程序&#xff0c;程序编好后需要树莓派使能程序开机自启动。其实这些方法对任何Linux系统都适用。 方法一&#xff1a;此方法的缺点是不进入默认pi的账号&#xff0c;甚至不开hdmi开启桌面的话&#xff0…

金融银行业更适合申请哪种SSL证书?

在当今数字化时代&#xff0c;金融行业的重要性日益增加。越来越多的金融交易和敏感信息在线进行&#xff0c;金融银行机构必须采取必要的措施来保护客户数据的安全。SSL证书作为一种重要的安全技术工具&#xff0c;可以帮助金融银行机构加密数据传输&#xff0c;验证网站身份&…

python动态圣诞下雪图

运行图片 代码 import pygame import random# 初始化Pygame pygame.init()# 创建窗口 width, height 800, 600 screen pygame.display.set_mode((width, height)) pygame.display.set_caption(Christmas Tree)# 定义颜色 GREEN (34, 139, 34) RED (255, 0, 0) WHITE (255…

centos7 安装java jdk1.8

1. jdk 百度云下载 2. 上传到服务器任意目录并解压&#xff1a; tar -zxvf jdk-8u231-linux-x64.tar.gz 3.配置环境变量 vim /etc/profile 在文件末尾添加如下命令&#xff0c;保存退出&#xff1a; export JAVA_HOME/opt/jdk1.8.0_231 export PATH$JAVA_HOME/bin:$PAT…

公众号50个数量怎么操作?

一般可以申请多少个公众号&#xff1f;公众号申请限额在过去几年内的经历了很多变化。对公众号申请限额进行调整是出于多种原因&#xff0c;确保公众号内容的质量和合规性。企业公众号的申请数量从50个到5个最后到2个&#xff0c;对于新媒体公司来说&#xff0c;这导致做不了公…

【Node.js】笔记整理 5 - Express框架

写在最前&#xff1a;跟着视频学习只是为了在新手期快速入门。想要学习全面、进阶的知识&#xff0c;需要格外注重实战和官方技术文档&#xff0c;文档建议作为手册使用 系列文章 【Node.js】笔记整理 1 - 基础知识【Node.js】笔记整理 2 - 常用模块【Node.js】笔记整理 3 - n…

低噪声,带内置 ALC 回路的双通道均衡放大器,应用于立体声收录机和盒式录音机的芯片D3308的描述

D3308 是一块带有 ALC 的双通道前置放大器。它适用于立体声收录机和盒式录音机。采用 SIP9、SOP14 的封装形式封装。 主要特点 带内置 ALC 回路的双通道均衡放大器 低噪声: VNIl.OuV(典型值)。开环电压增益高: 80dB (典型值)工作电源电压范围宽: 通道间的…

MyBatis查询优化:枚举在条件构建中的妙用

&#x1f680; 作者主页&#xff1a; 有来技术 &#x1f525; 开源项目&#xff1a; youlai-mall &#x1f343; vue3-element-admin &#x1f343; youlai-boot &#x1f33a; 仓库主页&#xff1a; Gitee &#x1f4ab; Github &#x1f4ab; GitCode &#x1f496; 欢迎点赞…