FileNotFoundException when calling webservice

后端 未结 5 836
天涯浪人
天涯浪人 2021-02-04 01:47

Hello I got past my initial problem. I\'m a total android noob, this is my first app. I\'m testing this on the Android emulator. I try to connect to a .NET webservice at h

5条回答
  •  情话喂你
    2021-02-04 02:38

    It's the same problem I was having: HttpUrlConnection returns FileNotFoundException if you try to read the getInputStream() from the connection.
    You should instead use getErrorStream() when the status code is higher than 400.

    More than this, please be careful since it's not only 200 to be the success status code, even 201, 204, etc. are often used as success statuses.

    Here is an example of how I went to manage it

    ... connection code code code ...
    
    // Get the response code 
    int statusCode = connection.getResponseCode();
    
    InputStream is = null;
    
    if (statusCode >= 200 && statusCode < 400) {
       // Create an InputStream in order to extract the response object
       is = connection.getInputStream();
    }
    else {
       is = connection.getErrorStream();
    }
    
    ... callback/response to your handler....
    

    In this way, you'll be able to get the needed response in both success and error cases.

    Hope this helps!

提交回复
热议问题