【问题标题】:IOException: Server returned 400 error codeIOException:服务器返回 400 错误代码
【发布时间】:2019-11-14 09:19:04
【问题描述】:

嗨,下面是一段代码。在下面的代码中,当我在写入后关闭写入器时,服务器会给出预期的结果。但是如果它在 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.write(ip);之后执行writer.flush()

标签: java exception ioexception


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2014-03-14
    • 2020-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多