在Android UrlConnection中未识别出具有不同错误消息的Http 404

时间:2015-08-03 10:49:10

标签: android httpurlconnection filenotfoundexception

默认情况下,如果服务器抛出404,那么android HTTPUrlConnection会假定FileNotFoundException。

但是服务器根据一些自定义服务器实现提供了一些错误消息

如何捕获此erorr消息以及FileNotFoundException

try{
    urlConnection = url.openConnection();
    urlConnection.connect();
    .....//get http status and message
    .....
    if(httpStatus >= 200 && httpStatus < 300){
         ins = urlConnection.getInputStream();
    }
} catch (SocketTimeoutException e) {
    Log.debug("Timeout in REST URL Connectivity");
} catch (FileNotFoundException e){
    //it automatically comes here even before I try to parse the error
    Log.debug("Requested HTTP URL does not exists");
} catch (IOException e) {
    Log.debug("Error processing REST URL Connectivity IO Streams");
}

服务器也可以在+ ve用例中返回404但具有不同的错误消息

   Code: 404
   Message: Request user does not exists

我们无法牺牲404错误代码,但UrlConnection假定根据404错误代码,URL本身不存在。

使用Google Chrome中的高级REST客户端进行测试

2 个答案:

答案 0 :(得分:0)

HttpUrlConnection为您提供了一个响应代码,在您的情况下为404.根据响应代码,您可以处理输入流或错误流。如果responseCode为404,则无法读取输入流。 例如:

c = (int)c + 1;    //By force conversion from character to integer to get the ASCII value

答案 1 :(得分:0)

所以我终于弄清楚了这个问题,Java从JSON格式读取错误。因此,如果您的JSON具有status =“ error”,则它将视为Error并抛出404或任何其他代码。 但是,如果您使用以下代码,则可以检索响应:

 if(httpStatus != 200 ){
         ins = urlConnection.getInputStream();
    }else{
      ins = urlConnection.getErrorStream();   // This is what will give you the data you are looking for
    }

希望这会有所帮助。它为我提供了Android中的Wordpress API的帮助。