Search code examples
javaandroidsocketsurlinputstream

Differentiate Common Http Errors in URL.openStream()


I am quite stuck as I have to differentiate common HTTP Errors occurred during Url.openStream(). Main purpose is to identify following HTTP Get request errors:

  1. 400 (bad request)
  2. 401 (unauthorized)
  3. 403 (forbidden)
  4. 404 (not found)
  5. 500 (internal server error)

Till now i could identify only 404 by catching FileNotFoundException. This is my code snippet:

try {
    file.createNewFile();
    URL url = new URL(fileUrl);
    URLConnection connection = url.openConnection();
    connection.connect();

    // download the file
    InputStream input = new BufferedInputStream(url.openStream());

    // store the file
    OutputStream output = new FileOutputStream(file);

    byte data[] = new byte[1024];
    int count;
    while ((count = input.read(data)) != -1) {
        output.write(data, 0, count);
        Log.e(TAG, "Writing");
    }

    output.flush();
    output.close();
    input.close();
    result = HTTP_SUCCESS;
} catch (FileNotFoundException fnfe) {
    Log.e(TAG, "Exception found FileNotFoundException=" + fnfe);
    Log.e(TAG, "FILE NOT FOUND");
    result = HTTP_FILE_NOT_FOUND;
} catch (Exception e) {
    Log.e(TAG, "Exception found=" + e);
    Log.e(TAG, e.getMessage());
    Log.e(TAG, "NETWORK_FAILURE");
    result = NETWORK_FAILURE;
}

It may be a small problem but I am totally clueless.


Solution

  • If you use HTTP cast your connection to HttpUrlConnection and before open stream check response status code using connection.getResponseCode():

    connection = (HttpURLConnection) new URL(url).openConnection();
    /* ... */
    final int responseCode = connection.getResponseCode();
    switch (responseCode) {
      case 404:
      /* ... */
      case 200: {
        InputStream input = new BufferedInputStream(url.openStream());
        /* ... */
      }
    }
    

    And do not forget close connection in finally block.