java - IOException:服务器返回 400 错误代码
问题描述
嗨下面是一段代码。在下面的代码中,当我在写入后关闭写入器时,服务器会给出预期的结果。但是如果它在 finally 块中关闭,它会返回 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()。
推荐阅读
- ruby-on-rails - IoT 模块与 AWS EC2 服务器的通信
- reactjs - 如何在我的网站上使用来自 Github 的 react 项目
- java - 如何在对话框之间发送数据?
- tensorflow - 如何提取训练模型的损失函数?
- c# - 使用 RestSharp 的多个请求(分页)
- javascript - 带有 try catch 的 ChartJs
- html - Safari 无法正确转换详细信息/摘要元素
- javascript - 以“#”和“.”为前缀的单元测试命名约定的名称是什么?在测试名称中?
- ipad - 网页设计:Elementor 响应模式菜单不起作用
- c# - 我的脚本让玩家连续跳跃,我想让它跳跃一次或两次