首页 > 解决方案 > 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();
    }             
}

标签: javaexceptionioexception

解决方案


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


推荐阅读