Java URL连接:如何获取返回状态的正文!=200?
我有一个Web服务,有时返回401状态。 它附带一个JSON主体,类似于:Java URL连接:如何获取返回状态的正文!=200?,java,gson,httpurlconnection,Java,Gson,Httpurlconnection,我有一个Web服务,有时返回401状态。 它附带一个JSON主体,类似于: {"status": { "message" : "Access Denied", "status_code":"401"}} 下面是我用来发出服务器请求的代码: HttpURLConnection conn = null; try{ URL url = new URL(/* url */); conn = (HttpURLConnection)url.openConnection(); //this ca
{"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);
}
在堆栈溢出数据库中进行粗略搜索可能会找到提及此解决方案的地方。在响应状态为200的情况下,用于读取的代码在哪里?我在任何地方都看不到。首先在任何Web服务工具(如SOAPUI)中尝试Web服务url,并确定给定requestAdded代码的响应,以便在状态为200的情况下处理响应…问题不是响应,问题是在返回代码的情况下,java.net.url显然无法检索响应正文=200..