java - URL 连接 : how to get body returned with status ! = 200?

标签 java gson httpurlconnection

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

相关文章:

java - Bouncy CaSTLe FIPS 库中缺少 EC.generateKeyPair()

java - Gson 抛出 MalformedJsonException 和其他异常

java - IOException,HTTP 响应代码为 : 400 occurs intermittently and works after server restart

java - 发送 GET 请求后,HttpURLConnection 返回响应代码 500,即使它在本地工作

java - 构建部署基础知识

java - 如何在需要注入(inject)实例的 Guice 中进行动态绑定(bind)?

java - 如何获取机器的mac地址

java - String 类的 Gson 自定义反序列化器

java - 如果没有用Gson初始化如何不写float(GsonBuilder())

java - REST HttpURL 连接