版权声明:需要引用、发表的朋友请与本人联系 https://blog.csdn.net/pbrlovejava/article/details/88911406
JXVB是一款由Java开发的框架,用于对xml进行一些操作。
使用JAXB的原因是这个项目中使用到大量的第三方接口,而这些第三方接口需要使用xml作为请求,所以自然而然地学习了JAXB,并且结合了HttpClient完成了一个通用的工具类,不了解JAXB和HttpClient的同学请自行google学习。
- XmlClientUtil
public class XmlClientUtil {
/**
* @param url
* @param xmlContent
* @auther: Arong
* @description: 发送xml请求到server端, 返回xml的String内容
* @return: java.lang.String
* @date: 2019/3/2 15:29
*/
public static String sendPostWithXml(String url, String xmlContent) {
//创建httpclient工具对象
//HttpClient client = new HttpClient();
CloseableHttpClient client = HttpClients.createDefault();
//创建post请求方法
// PostMethod myPost = new PostMethod(url);
HttpPost myPost = new HttpPost(url);
//设置请求超时时间
// client.setConnectionTimeout(3000 * 1000);
String responseString = null;
try {
//设置请求头部类型
myPost.setHeader("Content-Type", "text/xml");
myPost.setHeader("charset", "utf-8");
// myPost.setRequestHeader("Content-Type", "text/xml");
// myPost.setRequestHeader("charset", "utf-8");
//设置请求体,即xml文本内容,一种是直接获取xml内容字符串,一种是读取xml文件以流的形式
StringEntity xmlParams = new StringEntity(xmlContent, "utf-8");
myPost.setEntity(xmlParams);
// myPost.setRequestBody(xmlString);
CloseableHttpResponse response = client.execute(myPost);
//只有请求成功200了,才做处理
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
//获取返回的xml信息成String
responseString = EntityUtils.toString(response.getEntity(), "utf-8");
//System.out.println(body);
// InputStream inputStream = myPost.getResponseBodyAsStream();
// BufferedReader br = new BufferedReader(new InputStreamReader(inputStream, "utf-8"));
// StringBuffer stringBuffer = new StringBuffer();
// String str = "";
// while ((str = br.readLine()) != null) {
// stringBuffer.append(str);
// }
// responseString = stringBuffer.toString();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
client.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return responseString;
}
/**
* @param params 变长参数,约定第一个参数为xmlContent,第二个为url,第二个为空即使用默认地址
* @auther: Arong
* @description: 将URL转化为PMS URL
* @return: java.lang.String
* @date: 2019/3/2 19:24
*/
public static String getMd5Url(String... params) {
//基础地址
String baseUrl = "http://pmsnotify.gshis.com/DataExchange";
//md5地址
String md5Url = "";
//16位秘钥
String secureKey = PmsConfig.secretKey;
//集团id(酒店id)
String grpId = PmsConfig.grpid;
//渠道,默认为C01
String channel = PmsConfig.channel;
//以上三者+完整的xml请求生成md5标识
String sign = MD5Util.getMd5(new StringBuffer(secureKey).append(grpId).append(channel).append(params[0]).toString());
//判断是否有确定地址
if (params.length >= 2) {
//有确定地址,返回确定地址的md5加密版本
md5Url = new StringBuffer(params[1])
.append("?grpId=")
.append(grpId)
.append("&channel=")
.append(channel)
.append("&sign=")
.append(sign)
.toString();
}
//使用基础地址加密
md5Url = new StringBuffer(baseUrl)
.append("?grpId=")
.append(grpId)
.append("&channel=")
.append(channel)
.append("&sign=")
.append(sign)
.toString();
return md5Url;
}
/**
* @param object
* @auther: Arong
* @description: 将Object转化为XML字符串
* @return: java.lang.String
* @date: 2019/3/2 21:28
*/
public static String convertObjectToXML(Object object) {
Class<?> aClass = object.getClass();
Marshaller marshaller = null;
//用字符写入流获取字符串
StringWriter sw = new StringWriter();
try {
//执行器
JAXBContext context = JAXBContext.newInstance(aClass);
//获得编组用于序列化
marshaller = context.createMarshaller();
//格式化xml输出
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
// marshaller.marshal(object,System.out);
marshaller.marshal(object, sw);
} catch (JAXBException e) {
e.printStackTrace();
}
return sw.toString();
}
@Deprecated
public static Object convertXMLToObject(String xml, Object object) {
Class<?> aClass = object.getClass();
Object xmlObject = null;
try {
JAXBContext context = JAXBContext.newInstance(aClass);
Unmarshaller unmarshaller = context.createUnmarshaller();
StringReader sr = new StringReader(xml);
xmlObject = unmarshaller.unmarshal(sr);
} catch (JAXBException e) {
e.printStackTrace();
}
return xmlObject;
}
@Deprecated
public static Object getObject(Object xmlRequestObject, Object xmlResponseObject) {
String xmlContent = convertObjectToXML(xmlRequestObject);
String md5Url = getMd5Url(xmlContent);
String xmpResponse = sendPostWithXml(md5Url, xmlContent);
System.out.println("xmlContent:" + xmlContent);
System.out.println("xmlResponse:" + xmpResponse);
Object o = convertXMLToObject(xmpResponse, xmlResponseObject);
return o;
}
/**
* @param javaBean
* @auther: Arong
* @description: 传入封装了请求参数的javaBean,
* 在此方法内将其简化为xml并发送带xml参数的md5请求,然后将获得的响应转化为JSONObject
* @return: net.sf.json.JSONObject
* @date: 2019/3/4 12:16
*/
public static JSONObject postWithRequestJavaBean(Object javaBean) {
//1、将JavaBean转化为XML
String xmlContent = convertObjectToXML(javaBean);
//2、确定xmlContent不为空则发送md5请求获取xmlResponse
Optional.ofNullable(xmlContent)
.orElseThrow(() -> new RuntimeException("xmlContent为空"));
System.out.println("xml request:------------------\n" + xmlContent);
//获取到xml请求后的xmlResponse
String xmlResponse = XmlClientUtil.sendPostWithXml(XmlClientUtil.getMd5Url(xmlContent), xmlContent);
System.out.println("xml response:------------------\n" + xmlResponse);
//初始化XMLSerializer
XMLSerializer xmlSerializer = new XMLSerializer();
//将xmlResponse解析为jsonString
String jsonString = xmlSerializer.read(xmlResponse).toString();
//确定jsonString不为空则将其解析为JSONObject
JSONObject jsonObject = Optional.ofNullable(jsonString)
.map(s -> {
//不为空将其解析为JSONObject
JSONObject jobj = JSONObject.fromObject(jsonString);
return jobj;
})
.orElseThrow(() -> new RuntimeException("jsonString为空!"));
//异常检查
ExceptionHander.handlerException(jsonObject);
return jsonObject;
}
}