• 通过request请求获取<xml>


    使用io流完成request传参,获取<xml>,具体代码如下:

    public Object getParameter(HttpServletRequest request, HttpServletResponse response){

    request.setCharacterEncoding("UTF-8");//设置字符格式
    response.setCharacterEncoding("UTF-8");
    response.setContentType("text/html;charset=UTF-8");
    response.setHeader("Access-Control-Allow-Origin", "*");
    // achieve input stream
    InputStream in = request.getInputStream();
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    // length of string
    byte[] buffer = new byte[1024];
    int len = 0;
    // achieve data from in
    while ((len = in.read(buffer)) != -1) {
    out.write(buffer, 0, len);
    }
    in.close();
    out.close();

    //获取流对象内容

    String content = new String(out.toByteArray(), "utf-8");
    //获取json对象

    JSONObject jsonObject = JSONObject.parseObject(XmltoJsonUtil.xml2JSON(content));
    //获取xml对象
    JSONObject result_xml = jsonObject.getJSONObject("xml");
    // 获取<xml>中某个对象具体的值
    JSONArray return_code = result_xml.getJSONArray("return_code");
    String code = return_code.get(0).toString();

    System.out.println("code:"+code);

    }

    //<xml>转为json格式

    public class XmltoJsonUtil {
    public static String xml2JSON(String xml) {
    JSONObject obj = new JSONObject();
    try {
    InputStream is = new ByteArrayInputStream(xml.getBytes("utf-8"));
    SAXBuilder sb = new SAXBuilder();
    Document doc = sb.build(is);
    Element root = doc.getRootElement();
    obj.put(root.getName(), iterateElement(root));
    return obj.toString();
    } catch (Exception e) {
    e.printStackTrace();
    return null;
    }
    }

    eg:输入的<xml>对象为:

    <xml>
    <return_code>SUCCESS</return_code>
    <appid><![CDATA[wx2421b1c4370ec43b]]></appid>
    <mch_id><![CDATA[10000100]]></mch_id>
    <nonce_str><![CDATA[TeqClE3i0mvn3DrK]]></nonce_str>

    </xml>

    输出结果为:

    code:SUCCESS

  • 相关阅读:
    求给定数里的数的质数最大——pku3048
    poj1106
    poj1450
    poj1094
    poj1111
    poj1120
    C#.NET学习笔记 类,接口,对象
    在Repeater中嵌套使用Repeater
    数据表分区解决方案(转)
    C#小数点格式化
  • 原文地址:https://www.cnblogs.com/qqzhulu/p/10371696.html
Copyright © 2020-2023  润新知