tags:

views:

48

answers:

1

I am using Http get and post methods for Http Connection I just wanted to ask that what all exception can occur in using them. I know list may be too long but can someone tell me the general and frequent exceptions that occur and must be handled? my code is :

public class httpconnection
    {

    HttpClient client=new DefaultHttpClient();
      InputStream in=null;


    public InputStream httpreponse_post(String url,List<NameValuePair> params)
     {
      try {

    HttpPost post = new HttpPost(url); 
        UrlEncodedFormEntity ent = new UrlEncodedFormEntity(params,HTTP.UTF_8);
        post.setEntity(ent);
        HttpResponse responsePOST = client.execute(post);  
        HttpEntity resEntity = responsePOST.getEntity();  
        in=resEntity.getContent();
        in.close();

} catch (ClientProtocolException e)
 {
 Log. e ("Client Protocol Exception", e.toString ());
 }
 catch (IOException e) {
 Log. e ("Input Output Exception", e.toString ());
  }
  return in;
    }



 public InputStream httpreponse_get(String url)
  {
     try 
    {


  //String getURL = "http://www.google.com";
 HttpGet get = new HttpGet(url);
 HttpResponse responseGet = client.execute(get);
 HttpEntity resEntityGet = responseGet.getEntity();
     in=resEntityGet.getContent();
     in.close();
 } 

 catch (IOException e) {
 Log. e ("Input Output Exception", e.toString ());
  }
  return in;
        }
     }
+3  A: 

Here's a few exception that you should at least include them in your code:

catch (UnsupportedEncodingException e)  //POST section
catch (NullPointerException e) //POST & GET section
catch (ClientProtocolException e)  //POST section
catch (IOException e) // POST & GET section

And if you need to make sure to catch any other exceptions that might occur besides mentioned above, just add the general exception on the last catch statement. That should get your code covered.

catch (Exception e)
anmustangs
Thanx ...I did add them in my code.It was really helpful.but what happens when there is a network timeout?
shaireen
IOException already handled that, but if you need to be more specific, use ConnectTimeoutException (before IOException catch block). You're welcome shaireen.
anmustangs
Thanx a lot for the help.. :)
shaireen