1

不是我其他问题的重复。

我正在发送这样的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();

如何读取从 HTTPPOST请求返回的 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();
4

2 回答 2

1

不要使用ReadersandreadLine()与 xml 数据。使用InputStreamsbyte[]s。

于 2013-04-09T00:55:36.273 回答
1

感谢 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);
于 2013-04-09T01:12:49.137 回答