[英]How to read XML returned by HTTP POST request?
不能重復我的其他問題。
我正在發送這樣的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();
不要將Readers
和readLine()
與xml數據一起使用。 使用InputStreams
和byte[]
。
感謝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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.