我的网络服务有时会返回状态 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 只给我一个通用的“未经授权”...那么如何检索该 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其中提到了这个解决方案。
关于java - URL 连接 : how to get body returned with status ! = 200?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32073508/