XML格式发送和返回数据

以xml格式向远程服务器发送数据请求,以如下xml格式为例进行数据拼接,并进行发送

xml:

<TCSTrCmd.Req>
  <MsgHeader>
    <TrId>2018-001</TrId>
    <CmdType>GetTemplateDetailByName</CmdType>
  </MsgHeader>
  <TrJobs>
    <TrJob>volumn</TrJob>
  </TrJobs>
</TCSTrCmd.Req>

对xml进行数据拼接:

Element rootReq = DocumentHelper.createElement("TCSTrCmd.Req");
Document trCmdReq = DocumentHelper.createDocument(rootReq);
Element header = rootReq.addElement("MsgHeader");
header.addElement("TrId").addText("2018-001");
header.addElement("CmdType").addText("GetTemplateDetailByName");
Element trJobs = rootReq.addElement("TrJobs");
trJobs.addElement("TrJob").addText("volumn");

StringWriter out=null;  
try{  
    OutputFormat formate=OutputFormat.createPrettyPrint();  
    out=new StringWriter();  
    XMLWriter writer=new XMLWriter(out,formate);  
    writer.write(transcodeCmdReq);
} catch (IOException e){  
    e.printStackTrace();  
} finally{
    out.close();   
}        
String result="";		
result  = httpClient("http://"+ Ip +":"+ Port + "url路径", out.toString());
if(result == null){
    return "";
}

返回的数据依然为xml格式,如下:

<TCSTrCmd.Resp>
    <MsgHeader>
        <TrId>2018-001</TrId>
        <CmdType>GetTemplateDetailByName</CmdType>
    </MsgHeader>
    <TrJobs>
        <Tr>
            <Name>volumn</Name>
            <Detail>{"name":"volumn","horizontalResolution":720,"keyFrameInterval":50,"macroCellSearch":64,"resolution":"720x576","verticalResolution":576}</Detail>
        </Tr>
    </TrJobs>
</TCSTrCmd.Resp>

对返回数据进行解析,需要得到<Detail>标签当中的数据:

Document transcodeCmdResp = DocumentHelper.parseText(result); 
Element rootResp = transcodeCmdResp.getRootElement();
boolean flag = true;
Iterator item1 = rootResp.elementIterator("MsgHeader");
while(item1.hasNext()){
    Element msgHeader = (Element) item1.next();
    String trId = msgHeader.elementTextTrim("TrId");
    String cmdType = msgHeader.elementTextTrim("CmdType");
    if(trId.equals("2018-001")&&cmdType.equals("GetTemplateDetailByName")){
	flag=true;
    }else{
        flag=false;
    }
}
Iterator item2 = rootResp.elementIterator("TrJobs");
String templateDetail = "";
while(flag&&item2.hasNext()){
    Element TrJobs = (Element) item2.next();
    Iterator tr = TrJobs.elementIterator("TrJob");
    while(tr.hasNext()){
	Element template = (Element) tr.next();
	templateDetail = template.elementTextTrim("Detail");
    }
}

<Detail>标签中的数据已经全部存入字符串templateDetail当中,假设需要获取字符串templateDetail中horizontalResolution和verticalResolution所对应的值

JSONObject myJsonObject = JSONObject.parseObject(cmdStr);
templateInfoParser.setTempJsonObject(myJsonObject);
String vertical = templateInfoParser.getVerticalResolution();
String horizontal = templateInfoParser.getHorizontalResolution();

templateInfoParser类如下所示:

import org.springframework.stereotype.Service;
import com.alibaba.fastjson.JSONObject;
@Service
public class TemplateInfoParser {
	private JSONObject tempJsonObject;
	public void setTempJsonObject(JSONObject tempJsonObject) {
		this.tempJsonObject = tempJsonObject;
	}
	public String getVerticalResolution() {
        return getOutput1Video1VO().getString("verticalResolution");
    }
    public String getHorizontalResolution() {
        return getOutput1Video1VO().getString("horizontalResolution");
    }

    public String getResolution() {
        String horizontalResolution = getHorizontalResolution();
        String verticalResolution = getVerticalResolution();
        if (horizontalResolution != null && verticalResolution != null) {
            return new StringBuilder().append(horizontalResolution).append("*").append(verticalResolution).toString();
        }
        return null;
    }

    private JSONObject getOutput1Video1VO() {
        JSONObject output1Video1VO = tempJsonObject
                .getJSONObject("outputMap").getJSONObject("items")
                .getJSONObject("output1").getJSONObject("videoMap")
                .getJSONObject("items").getJSONObject("output1-video1")
                .getJSONObject("vo");
        return output1Video1VO;
    }
}
现已完成对xml数据的发送以及返回结果的解析,其中 httpClient方法如下:
public static String httpClient(String accessUrl, String paramStr) throws CommonException {
        String retMessage = null;
        try {
            URL url = new URL(accessUrl);
            // 发送POST请求必须设置如下两行  
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();

            conn.setDoInput(true);
	    conn.setDoOutput(true);
	    conn.setUseCaches(false);
	    conn.setInstanceFollowRedirects(true);
	    conn.setRequestMethod("POST");
	    conn.setRequestProperty("Cache-Control", "no-cache");
	    conn.setRequestProperty("Accept-Charset", "utf-8");
	    conn.setRequestProperty("contentType", "utf-8");
	    conn.setRequestProperty("Content-Type",   "multipart/form-data; charset=UTF-8; ");  //解决乱码问题
	    conn.setRequestProperty("Content-Length", String.valueOf(paramStr.length()));
            conn.connect();
            conn.setConnectTimeout(120000);
            conn.setReadTimeout(120000);
     

            DataOutputStream out = new DataOutputStream(conn.getOutputStream());
            byte[] bytes = paramStr.getBytes("utf-8"); 
            out.write(bytes, 0, bytes.length);
            out.flush();

//            responseCode = conn.getResponseCode();
            BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(),"UTF-8"));
            String line = null;
            StringBuffer sb = new StringBuffer();
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }

            //使用httpURLConnection.getResponseMessage()可以获取到[HTTP/1.0 200 OK]中的[OK]  
            String respResult = conn.getResponseMessage();
            if ("OK".equals(respResult)) {
            	retMessage = sb.toString();
            }
            conn.disconnect();
        } catch (Exception e) {
        	//throw new CommonException(ErrorCodes.HTTPCLIENT_ERR);
        	
        }
        return retMessage;
    }

如果xml中存在属性,进行如下拼接:

trJobs.addElement("Tr").addAttribute("属性名", "属性值");


  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值