gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 17:10:53 26 4
gpt4 key购买 nike

与我的其他问题不重复。

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

最佳答案

不要对 xml 数据使用 ReadersreadLine()。使用 InputStreamsbyte[]

关于java - 如何读取 HTTP POST 请求返回的 XML?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15891051/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com