不是我其他问题的重复。
我正在发送这样的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();