1、要拼装的xml报文格式为:
2、拼装报文,并调用接口
/**
* 拼装报文,调用接口
*
* @param jsonData 传送的报文body内容
* @param tranId 接口id
* @return
*/
public String callService(String jsonData,String tranId) {
//拼装报文
Document document = DocumentHelper.createDocument();
Element service = document.addElement("service");
Element head = service.addElement("head");
head.addElement("tran_id").setText(tranId);
head.addElement("tran_seq");
head.addElement("channel_id").setText(clientId);
head.addElement("clientVersion").setText("v1");
head.addElement("password").setText(clientPassword);
Element body = service.addElement("body");
//设置body内容
body.addCDATA(jsonData);
String text = document.asXML();
try {
//Http协议调用接口,其中serviceBusURI是要调用地址
URL url = new URL(serviceBusURI);
URLConnection con = url.openConnection();
con.setDoOutput(true);
con.setRequestProperty("Pragma:", "no-cache");
con.setRequestProperty("Cache-Control", "no-cache");
//设置编码,不然返回报文格式乱码
con.setRequestProperty("Content-Type", "text/xml;charset=UTF-8");
OutputStreamWriter out = new OutputStreamWriter(con.getOutputStream());
out.write(new String(text.getBytes("UTF-8")));
out.flush();
out.close();
//返回数据
BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(),"utf-8"));
String line = "";
//存放请求内容
StringBuffer xml = new StringBuffer();
while ((line = br.readLine()) != null) {
xml.append(line);
}
//解析报文,字符串转XML
Document doc = DocumentHelper.parseText(xml.toString());
Element root = doc.getRootElement();
Element rtnCode=root.element("head").element("rtnCode");
if("0000".equals(rtnCode.getTextTrim())){
Element node=root.element("body");
return node.getStringValue();
}else {
log.error(String.format("返回报文失败:%s", xml.toString()));
}
} catch (Exception e) {
log.error("调用远程服务出现问题",e);
}
return null;
}
3、返回xml报文,转换成实体类
//将字符串转换为实体类
JSONObject jsStr = JSONObject.parseObject(reXml);
XxtxConfig dbDto = (XxtxConfig) JSONObject.toJavaObject(jsStr, XxtxConfig.class);
END.2018.12.29