强制 java.net.HttpUrlConnection 到 return GET 响应,不管 Http-Status-Code
Force java.net.HttpUrlConnection to return GET-response regardless of Http-Status-Code
我正在使用 HTTP 客户端将 GET 请求发送到 API,即使 HTTP 状态代码包含错误,它也会以正确的 JSON 对象进行响应,例如401.
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-- 用于在出现错误的情况下获取负载。
我正在使用 HTTP 客户端将 GET 请求发送到 API,即使 HTTP 状态代码包含错误,它也会以正确的 JSON 对象进行响应,例如401.
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-- 用于在出现错误的情况下获取负载。