【问题标题】:URL connection: how to get body returned with status != 200?URL 连接:如何以状态返回正文!= 200?
【发布时间】:2015-08-18 13:14:01
【问题描述】:

我有一个网络服务有时会返回状态 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?

【问题讨论】:

    标签: java gson httpurlconnection


    【解决方案1】:

    在非 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

    【讨论】:

      猜你喜欢
      • 2018-06-16
      • 1970-01-01
      • 2020-09-02
      • 2015-10-13
      • 2013-12-26
      • 1970-01-01
      • 2019-12-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多