如何读取HTTP POST请求返回的XML?

时间:2013-04-08 23:55:02

标签: java xml http post httpurlconnection

与我的其他问题不重复。

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

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分: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);
相关问题