2015-08-03 57 views
0

默认情况下,如果服务器抛出404,则android HTTPUrlConnection将假定FileNotFoundException。HTTP 404不同的错误信息在Android UrlConnection中未标识

但是提供了基于一些自定义服务器实现

一些错误消息如何与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"); 
} 

一起抓住这个erorr消息的服务器的服务器会返回404 +已经使用案例也有不同的错误信息

Code: 404 
    Message: Request user does not exists 

我们不能牺牲404错误代码,但UrlConnection假定URL本身不存在基于404错误代码。

测试与高级REST客户在谷歌浏览器

+0

你总是可以尝试使用'getErrorStream()'...问题是,一些'HTTPUrlConnection'实现我'FileNotFoundException'即使实际上它是* 500内部服务器错误* - 在这种情况下,我总是尝试“将HTTPUrlConnection转换为apach http客户端”(或使用一些工具,如fiddler2来产生相同的错误),并检查 – Selvin

回答

0

HttpURLConnection的给你一个responseCode,你的情况404.根据响应代码,你处理的InputStream或errorstream。您无法读取的InputStream如果responseCode是404 例子:

  int httpResult = urlConnection.getResponseCode(); 
      if (httpResult != HttpURLConnection.HTTP_OK) { 
       Log.e(TAG, urlConnection.getResponseMessage()); 
      } 
+0

之前发生了什么,但之前到达这个代码本身它会去try catch部分,我应该删除try catch部分吗? – Dickens

+0

如果它没有到达getResponseCode部分,则URL无效。这意味着,你不会像你说的那样得到404,你根本就没有服务器。你有没有像RestClient一样测试过你的url? – Christine

+0

是的,我测试过的服务器会在+ ve场景中返回404也有不同的消息,但是android假定这个URL本身不存在,并且我们不能牺牲404错误代码 – Dickens