我想向自己编写的HTTP Servlet发送POST请求。使用URL.openConnection()方法可以正常工作(HTTP响应代码为200)。但是如果我收到期望的错误响应代码(例如400),则认为我必须使用HttpUrlConnection.getErrorStream()。但是,即使在错误情况下我从servlet发送数据,ErrorStream对象也为空(我想评估此数据以生成错误消息)。 这是我的代码:
HttpURLConnection con = null;
try {
//Generating request String
String request = "request="+URLEncoder.encode(xmlGenerator.getStringFromDocument(xmlGenerator.generateConnectRequest(1234)),"UTF-8");
//Receiving HttpUrlConnection (DoOutput = true; RequestMethod is set to "POST")
con = openConnection();
if (con != null){
PrintWriter pw = new PrintWriter(con.getOutputStream());
pw.println(request);
pw.flush();
pw.close();
InputStream errorstream = con.getErrorStream();
BufferedReader br = null;
if (errorstream == null){
InputStream inputstream = con.getInputStream();
br = new BufferedReader(new InputStreamReader(inputstream));
}else{
br = new BufferedReader(new InputStreamReader(errorstream));
}
String response = "";
String nachricht;
while ((nachricht = br.readLine()) != null){
response += nachricht;
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
所以我的问题是,为什么调用getErrorStream()方法返回null,尽管状态码是400(我可以在调用con.getInputStream()时抛出的IOException中看到)。谢谢。