Android中的Http Get和Post方法异常?

时间:2010-10-22 03:43:01

标签: android http

我正在使用Http get和post方法进行Http Connection 我只是想问一下使用它们会发生什么异常。 我知道列表可能太长了但有人可以告诉我发生的一般和频繁的异常并且必须处理吗? 我的代码是:

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;
        }
     }

1 个答案:

答案 0 :(得分:5)

以下是一些例外,您至少应该在代码中包含它们:

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

如果您需要确保捕获除上面提到的可能发生的任何其他异常,只需在最后一个catch语句中添加常规异常。这应该涵盖您的代码。

catch (Exception e)