URL 连接:如何返回状态为 != 200 的正文?
URL connection: how to get body returned with status != 200?
我有一个 web 服务有时会返回状态 401。
它带有一个 JSON 主体,类似于:
{"status": { "message" : "Access Denied", "status_code":"401"}}
现在,这是我用来发出服务器请求的代码:
HttpURLConnection conn = null;
try{
URL url = new URL(/* url */);
conn = (HttpURLConnection)url.openConnection(); //this can give 401
JsonReader reader = new JsonReader(new InputStreamReader(conn.getInputStream()));
JsonObject response = gson.fromJson(reader, JsonObject.class);
//response handling
}catch(IOException ex){
System.out.println(conn.getResponseMessage()); //not working
}
当请求失败时,我想阅读那个 json 正文,但是 getResponseMessage 只给了我一个通用的 "Unauthorized"...那么如何检索那个 JSON?
在非200响应的情况下可以调用conn.getErrorStream()
:
HttpURLConnection conn = null;
try {
URL url = new URL(/* url */);
conn = (HttpURLConnection)url.openConnection(); //this can give 401
JsonReader reader = new JsonReader(new InputStreamReader(conn.getInputStream()));
JsonObject response = gson.fromJson(reader, JsonObject.class);
} catch(IOException ex) {
JsonReader reader = new JsonReader(new InputStreamReader(conn.getErrorStream()));
JsonObject response = gson.fromJson(reader, JsonObject.class);
}
通过 Stack Overflow 数据库进行粗略搜索会带您到 this article,其中提到了这个解决方案。
我有一个 web 服务有时会返回状态 401。 它带有一个 JSON 主体,类似于:
{"status": { "message" : "Access Denied", "status_code":"401"}}
现在,这是我用来发出服务器请求的代码:
HttpURLConnection conn = null;
try{
URL url = new URL(/* url */);
conn = (HttpURLConnection)url.openConnection(); //this can give 401
JsonReader reader = new JsonReader(new InputStreamReader(conn.getInputStream()));
JsonObject response = gson.fromJson(reader, JsonObject.class);
//response handling
}catch(IOException ex){
System.out.println(conn.getResponseMessage()); //not working
}
当请求失败时,我想阅读那个 json 正文,但是 getResponseMessage 只给了我一个通用的 "Unauthorized"...那么如何检索那个 JSON?
在非200响应的情况下可以调用conn.getErrorStream()
:
HttpURLConnection conn = null;
try {
URL url = new URL(/* url */);
conn = (HttpURLConnection)url.openConnection(); //this can give 401
JsonReader reader = new JsonReader(new InputStreamReader(conn.getInputStream()));
JsonObject response = gson.fromJson(reader, JsonObject.class);
} catch(IOException ex) {
JsonReader reader = new JsonReader(new InputStreamReader(conn.getErrorStream()));
JsonObject response = gson.fromJson(reader, JsonObject.class);
}
通过 Stack Overflow 数据库进行粗略搜索会带您到 this article,其中提到了这个解决方案。