gpt4 book ai didi

java - IOException:服务器返回 400 错误代码

转载 作者:行者123 更新时间:2023-12-02 03:33:14 24 4
gpt4 key购买 nike

嗨,下面是一段代码。在下面的代码中,当我在写入后关闭写入器时,服务器会给出预期的结果。但如果它在finally block 中关闭,它会返回400错误请求。这种行为有什么原因吗?

BufferedReader br = null;
HttpURLConnection conn = null;
OutputStreamWriter writer = null;
String ip = "test"
try {
URL url = new URL(http://someurl));
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setConnectTimeout(0);
conn.setRequestProperty("Content-Type", "application/json");
writer = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
writer.write(ip);
// writer.close();

br = new BufferedReader(new InputStreamReader(conn.getInputStream()));

String line;
while ((line = br.readLine()) != null) {
jsonString.append(line);
}
} catch (final Exception e) {
LOG.error("Error" + e);
}
finally
{
//Closing writer in finally block.
if(writer != null)
{
try
{
writer.close();
}
catch (IOException e) {
LOG.error("Error in closing Writer", e);
}
}
if (br != null)
{
try
{
br.close();
}
catch (final IOException e)
{
LOG.error("Error: ", e);
}
}
if(conn != null){
conn.disconnect();
}
}

最佳答案

您需要将内容刷新到服务器。完成写入请求后,在读取响应之前,使用 writer.flush() 而不是 writer.close()。

关于java - IOException:服务器返回 400 错误代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56874262/

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