【发布时间】:2020-09-29 15:56:04
【问题描述】:
我正在开发一个 HTTP 客户端以将 GET 请求发送到 API,即使 HTTP 状态代码包含诸如 401 之类的错误,该 API 也会使用正确的 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 错误处理自己。我怎样才能做到这一点?
【问题讨论】:
-
取决于哪个语句抛出异常。如果在connection.connect()之前抛出异常;你怎么能得到状态,因为你还没有连接到 URL?
标签: java http httpurlconnection http-status-codes