我正在开发一个HTTP客户端,向一个API发送GET-Requests,即使HTTP-Status Codes中包含401这样的错误,它也会用正确的JSON-Objects进行响应。
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,自己处理错误。我怎样才能实现这个目标?
我不相信你能做到 该但有 https:/docs.oracle.comjavase8docsapijavanetHttpURLConnection.html#getErrorStream--。 用于在发生错误时获取有效载荷。