URL连接:如何以状态返回正文!= 200?

时间:2015-08-18 13:14:02

标签: java gson httpurlconnection

我有一个webservice返回,有时,状态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?

1 个答案:

答案 0 :(得分:1)

如果是非200响应,您可以致电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); }

isPremium

通过Stack Overflow数据库进行粗略搜索会将您带到this article并提及此解决方案。