java - How to handle network state and HTTP status codes correctly -


Within one method, I am sending GET and POST requests using HttpURLConnection. As you can see in the example code, I am holding most exceptions. But I wonder if this is the right way and how should I actually manage a site like "no network is available" and bad status code in response to the server? I ask because of this because I want to inform the user about various problems.

  Public static bitmap getImage (string url) {HttpURLConnection conn = null; {URL new URL} Try new URL (URL); Conn = (HttpURLConnection) newUrl.openConnection (); Conn.setDoInput (true); Conn.setDoOutput (wrong); Conn.setUseCaches (wrong); Conn.setRequestProperty ("Accept-Charset", "utf-8"); Conn.setRequestProperty ("content type", "image / PNG"); Conn.setRequestMethod ("GET"); Conn.connect (); Int total = conn.getContentLength (); InputStream = conn.getInputStream (); // ... read the image here! } Catch (malmarmdureleuxation E) {e.printStackTrace (); Return tap; } Hold (NullPointerException e) {e.printStackTrace (); Return tap; } Hold (IOException e) {e.printStackTrace (); Return tap; } Finally {if (conn! = Null) conn.disconnect (); If (progress! = Null) progress .Set progress (1f); }}   

Use this to check whether the network is available or not < / P> Connectivity Manager Comgad = (Connectivity Manager) context.getSystemService (context.CONNECTIVITY_SERVICE); If (conMgr.getActiveNetworkInfo ()! = Null & amp; conMgr.getActiveNetworkInfo (.) Is available () & amp; amp; amp; conMgr.getActiveNetworkInfo () .isconnected ()) {// connection unavailable} else { // no connection}

If the connection is available then you can request http request & amp; Exception .getMessage () returns an appropriate error message that can be displayed to the user if there are any connections errors later.

Comments

Popular posts from this blog

Pass DB Connection parameters to a Kettle a.k.a PDI table Input step dynamically from Excel -

multithreading - PhantomJS-Node in a for Loop -

c++ - MATLAB .m file to .mex file using Matlab Compiler -