【问题标题】:How to read XML returned by HTTP POST request?如何读取 HTTP POST 请求返回的 XML?
【发布时间】:2013-04-08 23:55:02
【问题描述】:

不是我的其他问题的重复。

我正在发送这样的POST 请求:

        String urlParameters = "a=b&c=d";
        String request = "http://www.example.com/";

        URL url = new URL(request);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();      
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setInstanceFollowRedirects(false); 
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 
        connection.setRequestProperty("charset", "utf-8");
        connection.setRequestProperty("Content-Length", "" + Integer.toString(urlParameters.getBytes().length));
        connection.setUseCaches(false);

        DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
        wr.writeBytes(urlParameters);
        wr.flush();
        wr.close();
        connection.disconnect();

如何读取从 HTTP POST 请求返回的 xml 响应?特别是,我想将响应文件保存为 .xml 文件,然后读取它。对于我通常的GET 请求,我使用这个:

    SAXBuilder builder = new SAXBuilder();
    URL website = new URL(urlToParse);
    ReadableByteChannel rbc = Channels.newChannel(website.openStream());
    FileOutputStream fos = new FileOutputStream("request.xml");
    fos.getChannel().transferFrom(rbc, 0, 1 << 24);
    fos.close();
    // Do the work

附录:我正在使用以下代码,它工作得很好。但是,它忽略任何间距和换行,并将完整的 XML 内容视为单行。我该如何解决?

    InputStream is = connection.getInputStream();
    BufferedReader br = new BufferedReader(new InputStreamReader(is));
    StringBuilder sb1 = new StringBuilder();
    String line;
    while ((line = br.readLine()) != null) {
        sb1.append(line);
    }
    FileOutputStream f = new FileOutputStream("request.xml");
    f.write(sb1.toString().getBytes());
    f.close();
    br.close();

【问题讨论】:

  • 在完成对输出流的写入后,尝试从连接中获取输入流并从中读取?
  • @bdares 请参阅 OP 进行我的编辑。

标签: java xml http post httpurlconnection


【解决方案1】:

不要将ReadersreadLine() 用于xml 数据。使用InputStreamsbyte[]s。

【讨论】:

    【解决方案2】:

    感谢 Pangea,我修改了他的代码,现在可以使用:

        TransformerFactory transFactory = TransformerFactory.newInstance();
        Transformer t= transFactory.newTransformer();
        t.setOutputProperty(OutputKeys.METHOD, "xml");
        t.setOutputProperty(OutputKeys.INDENT,"yes");                
        Source input = new StreamSource(is);
        Result output = new StreamResult(new FileOutputStream("request.xml"));
        transFactory.newTransformer().transform(input, output);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-08-02
      • 1970-01-01
      • 2015-09-27
      • 2017-10-03
      • 1970-01-01
      • 2011-01-05
      • 2019-11-30
      • 1970-01-01
      相关资源
      最近更新 更多