2013-04-08 23 views
1

不是我的其他問題的副本。如何讀取HTTP POST請求返回的XML?

我送一個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

嘗試從連接獲取的InputStream從中讀取,你寫完你的OutputStream後,對不對? – bdares 2013-04-08 23:58:53

+0

@bdares請參閱OP進行編輯。 – 2013-04-09 00:45:36

回答

1

不使用ReadersreadLine() XML數據。使用InputStreamsbyte[] s。

1

感謝盤古,我修改了他的代碼,這現在工作:

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);