嗨,下面是这段代码。在下面的代码中,当我写完后关闭写程序时,服务器给出了预期的结果。但是,如果在最终阻止中关闭它,则会返回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();
}
}
答案 0 :(得分:0)
您需要将内容刷新到服务器。完成写入请求后,在读取响应之前,请使用writer.flush()而不是writer.close()。