java - Diffrentiate Common Http Errors in URL.openStream() -


i quite stuck i have differentiate common http errors occurred during url.openstream(). main purpose identify following http request errors:

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

till identify 404 catching filenotfoundexception. code snippet:

try {     file.createnewfile();     url url = new url(fileurl);     urlconnection connection = url.openconnection();     connection.connect();      // download file     inputstream input = new bufferedinputstream(url.openstream());      // store 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 small problem totally clueless. can please

if use http cast connection httpurlconnection , 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 not forget close connection in finally block.


Comments

Popular posts from this blog

php - Submit Form Data without Reloading page -

linux - Rails running on virtual machine in Windows -

php - $params->set Array between square bracket -