2015-08-18 23 views
1

我有一个web服务返回的,有时,状态401 它配备了一个JSON的身体,是这样的:URL连接:如何获得身体状态返回!= 200?

{"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?

+0

在响应状态为200的情况下,您正在使用的代码在哪里?我在任何地方都看不到。 –

+0

首先尝试任何Web服务工具,如SOAPUI中的webservice url,并确定给定请求的响应 –

+0

添加代码以处理状态为200的响应......问题不是响应,问题是显然是java的事实。 net.URL无法在返回代码!= 200时检索响应主体 – Phate

回答

1

您可以拨打conn.getErrorStream()在非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); 
} 

否则通过堆栈溢出数据库粗略搜索将带来你this article,其中提到该解决方案。

相关问题