Java:拼装解析XML报文,调用http接口返回数据

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

  • 2
    点赞
  • 50
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值