Android使用httpClient进行Post和Get发送参数 .

模拟发送Http请求我们可以使用HttpURLConnection类进行操作,但是Android平台集成了功能强大且编写更容易的commons-httpclient.jar,因此在这里介绍如何通过commons-httpclient进行Http请求。发送Http请求可以有两种方式:一种是同步,一种是异步。由于我对异步不是很熟悉,所以这里先提供同步方式发送Http请求:

1、使用Get方式发送

  1. public String httpGet(String url, String params) throws Exception   
  2.     {   
  3.         String response = null//返回信息    
  4.         if (null!=params&&!params.equals(""))   
  5.         {   
  6.             url += "?" + params;   
  7.         }   
  8.         // 构造HttpClient的实例    
  9.         HttpClient httpClient = new HttpClient();   
  10.         // 创建GET方法的实例    
  11.         GetMethod httpGet = new GetMethod(url);   
  12.         // 设置超时时间    
  13.         httpGet.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, new Integer(CONNECTION_TIMEOUT));   
  14.         try  
  15.         {   
  16.             int statusCode = httpClient.executeMethod(httpGet);   
  17.             if (statusCode == HttpStatus.SC_OK) //SC_OK = 200    
  18.             {   
  19.                 InputStream inputStream = httpGet.getResponseBodyAsStream(); //获取输出流,流中包含服务器返回信息    
  20.                 response = getData(inputStream);//获取返回信息    
  21.             }   
  22.             else  
  23.             {   
  24.                 LOG.debug("Get Method Statuscode : "+statusCode);   
  25.             }   
  26.         } catch (Exception e)   
  27.         {   
  28.             throw new Exception(e);   
  29.         } finally  
  30.         {   
  31.             httpGet.releaseConnection();   
  32.             httpClient = null;   
  33.         }   
  34.         return response;   
  35.     }   
public String httpGet(String url, String params) throws Exception 
    { 
        String response = null; //返回信息 
        if (null!=params&&!params.equals("")) 
        { 
            url += "?" + params; 
        } 
        // 构造HttpClient的实例 
        HttpClient httpClient = new HttpClient(); 
        // 创建GET方法的实例 
        GetMethod httpGet = new GetMethod(url); 
        // 设置超时时间 
        httpGet.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, new Integer(CONNECTION_TIMEOUT)); 
        try
        { 
            int statusCode = httpClient.executeMethod(httpGet); 
            if (statusCode == HttpStatus.SC_OK) //SC_OK = 200 
            { 
                InputStream inputStream = httpGet.getResponseBodyAsStream(); //获取输出流,流中包含服务器返回信息 
                response = getData(inputStream);//获取返回信息 
            } 
            else
            { 
                LOG.debug("Get Method Statuscode : "+statusCode); 
            } 
        } catch (Exception e) 
        { 
            throw new Exception(e); 
        } finally
        { 
            httpGet.releaseConnection(); 
            httpClient = null; 
        } 
        return response; 
    } 


 

2、使用Post方式发送

  1. public String httpPost(String url, List<Parameter> params) throws Exception   
  2.     {   
  3.         String response = null;   
  4.         HttpClient httpClient = new HttpClient();   
  5.         PostMethod httpPost = new PostMethod(url);   
  6.         //Post方式我们需要配置参数    
  7.         httpPost.addParameter("Connection""Keep-Alive");   
  8.         httpPost.addParameter("Charset""UTF-8");   
  9.         httpPost.addParameter("Content-Type""application/x-www-form-urlencoded");   
  10.         httpPost.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, new Integer(CONNECTION_TIMEOUT));   
  11.         if (null!=params&¶ms.size()!=0)   
  12.         {   
  13.             //设置需要传递的参数,NameValuePair[]    
  14.             httpPost.setRequestBody(buildNameValuePair(params));   
  15.         }   
  16.         try  
  17.         {   
  18.             int statusCode = httpClient.executeMethod(httpPost);   
  19.             if (statusCode == HttpStatus.SC_OK)   
  20.             {   
  21.                 InputStream inputStream = httpPost.getResponseBodyAsStream();   
  22.                 response = getData(inputStream);   
  23.             }   
  24.             else  
  25.             {   
  26.                 LOG.debug("Post Method Statuscode : "+statusCode);   
  27.             }   
  28.         } catch (Exception e)   
  29.         {   
  30.             throw new Exception(e);   
  31.         } finally  
  32.         {   
  33.             httpPost.releaseConnection();   
  34.             httpClient = null;   
  35.         }   
  36.         return response;   
  37.     }   
public String httpPost(String url, List<Parameter> params) throws Exception 
    { 
        String response = null; 
        HttpClient httpClient = new HttpClient(); 
        PostMethod httpPost = new PostMethod(url); 
        //Post方式我们需要配置参数 
        httpPost.addParameter("Connection", "Keep-Alive"); 
        httpPost.addParameter("Charset", "UTF-8"); 
        httpPost.addParameter("Content-Type", "application/x-www-form-urlencoded"); 
        httpPost.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, new Integer(CONNECTION_TIMEOUT)); 
        if (null!=params&¶ms.size()!=0) 
        { 
            //设置需要传递的参数,NameValuePair[] 
            httpPost.setRequestBody(buildNameValuePair(params)); 
        } 
        try
        { 
            int statusCode = httpClient.executeMethod(httpPost); 
            if (statusCode == HttpStatus.SC_OK) 
            { 
                InputStream inputStream = httpPost.getResponseBodyAsStream(); 
                response = getData(inputStream); 
            } 
            else
            { 
                LOG.debug("Post Method Statuscode : "+statusCode); 
            } 
        } catch (Exception e) 
        { 
            throw new Exception(e); 
        } finally
        { 
            httpPost.releaseConnection(); 
            httpClient = null; 
        } 
        return response; 
    } 


3、构件NameValuePair

  1. private NameValuePair[] buildNameValuePair(List<Parameter> params)   
  2.     {   
  3.         int size = params.size();   
  4.         NameValuePair[] pair = new NameValuePair[size];   
  5.         for(int i = 0 ;i<size;i++)   
  6.         {   
  7.             Parameter param = params.get(i);   
  8.             pair[i] = new NameValuePair(param.getName(),param.getValue());   
  9.         }   
  10.         return pair;   
  11.     }   
private NameValuePair[] buildNameValuePair(List<Parameter> params) 
    { 
        int size = params.size(); 
        NameValuePair[] pair = new NameValuePair[size]; 
        for(int i = 0 ;i<size;i++) 
        { 
            Parameter param = params.get(i); 
            pair[i] = new NameValuePair(param.getName(),param.getValue()); 
        } 
        return pair; 
    } 


4、获得返回数据

  1. private String getData(InputStream inputStream) throws Exception   
  2.     {   
  3.         String data = "";   
  4.         //内存缓冲区    
  5.         ByteArrayOutputStream outputStream = new ByteArrayOutputStream();   
  6.         int len = -1;   
  7.         byte[] buff = new byte[1024];   
  8.         try  
  9.         {   
  10.             while((len=inputStream.read(buff))!=-1)   
  11.             {   
  12.                 outputStream.write(buff, 0, len);   
  13.             }   
  14.             byte[] bytes = outputStream.toByteArray();   
  15.             data = new String(bytes);   
  16.         } catch (IOException e)   
  17.         {   
  18.             throw new Exception(e.getMessage(),e);   
  19.         }   
  20.         finally  
  21.         {   
  22.             outputStream.close();   
  23.         }   
  24.         return data;   
  25.     }   

猜你喜欢

转载自luke-feng.iteye.com/blog/1783595