[英]Force java.net.HttpUrlConnection to return GET-response regardless of Http-Status-Code
I'm working on a HTTP-Client to sent GET-Requests to an API, which responds with proper JSON-Objects even when the HTTP-Status Codes contains an Error such as 401.我正在使用 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;
}
When that's the case, the IOException is thrown and the response isn't written.在这种情况下,会抛出 IOException 并且不会写入响应。 However, I want to receive the response regardless of the HTTP-Status-Code and hande error handling myself.
但是,我想接收响应,而不管 HTTP-Status-Code 和hande 错误处理自己。 How can I achieve this?
我怎样才能做到这一点?
I don't believe you can do that , but there's https://docs.oracle.com/javase/8/docs/api/java/net/HttpURLConnection.html#getErrorStream-- for getting the payload in case of an error.我不相信你能做到这一点,但是有https://docs.oracle.com/javase/8/docs/api/java/net/HttpURLConnection.html#getErrorStream--用于在发生错误时获取有效负载.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.