问题描述
我想对自己编写的HTTP Servlet发出POST请求.通过使用URL.openConnection()方法,好的情况(HTTP响应代码200)始终可以正常工作.但是,当我收到所需的错误响应代码(例如400)时,我以为必须使用HttpUrlConnection.getErrorStream().但是,尽管我在错误情况下从servlet发送回数据,但ErrorStream对象为null(我想评估此数据以生成错误消息).这是我的代码:
I want to do a POST request to an HTTP Servlet I wrote myself. Good case (HTTP response Code 200) always works fine by using URL.openConnection() method. But when I receive a desired error response code (e.g. 400) then I thought I have to use HttpUrlConnection.getErrorStream(). But the ErrorStream object is null though I am sending data back from the servlet in error case (I want to evaluate this data to generate error messages).This is what my code looks like:
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();
}
所以我的问题是,为什么状态代码为400(为什么我可以在调用con.getInputStream()时抛出的IOException中看到它)却返回getErrorStream()null
So my question is, why returns getErrorStream() null though status code is 400 (I can see it in the IOException that is thrown when it calls con.getInputStream())
谢谢
推荐答案
来自getErrorStream()上的Java文档:
From the java documentation on getErrorStream():
因此,如果您未到达服务器(例如错误的URL)或服务器未在响应中发送任何内容,则getErrorStream()将返回null.
So if you didn't get to the server (bad url for example) or the server didn't send anything in the response, getErrorStream() will return null.
这篇关于HttpUrlConnection中的错误流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!