[英]Does java.net.HttpUrlConnection always throw IOException if there is an error status return by Server?
[英]Force java.net.HttpUrlConnection to return GET-response regardless of Http-Status-Code
我正在使用 HTTP 客户端将 GET 请求发送到 API,即使 HTTP 状态代码包含诸如 401 之类的错误,它也会以正确的 JSON 对象响应。
public String get(String url){
URL target;
HttpURLConnection connection;
int code = 200;
BufferedReader reader;
String inputLine;
String result = null;
try {
target = new URL(url);
} catch (MalformedURLException ex) {
return result;
}
try {
connection = (HttpURLConnection)target.openConnection();
connection.setRequestMethod("GET");
connection.connect();
//code = connection.getResponseCode();
reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
result = "";
while ((inputLine = reader.readLine()) != null){
result += inputLine;
}
reader.close();
} catch (IOException ex) {
return "...";
}
return result;
}
在这种情况下,会抛出 IOException 并且不会写入响应。 但是,我想接收响应,而不管 HTTP-Status-Code 和hande 错误处理自己。 我怎样才能做到这一点?
我不相信你能做到这一点,但是有https://docs.oracle.com/javase/8/docs/api/java/net/HttpURLConnection.html#getErrorStream--用于在发生错误时获取有效负载.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.