Android如何发送HTTP请求

本文深入解析Android SDK中的HttpClient,重点讲解HTTP GET和POST请求的实现过程,包括创建HttpClient对象、实例化HTTP GET或POST请求、设置请求参数、执行HTTP调用以及处理响应内容。

Android SDK提供HttpClient,和J2EE中的接口非常相似。最常用的就是HTTP GET和HTTP POST。

HTTP GET方式

public class HttpGetDemo extends Activity{  
    @Override 
    protected void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState); 
        setContentView(R.layout.activity_main);  
                 
        BufferedReader in = null; 
        try{  
            //【Step 1】创建一个HttpClient的对象(或使用已有的)
            HttpClient client = new DefaultHttpClient(); 
            //【Step 2】实例化一个HTTP GET或者HTTP POST,本例是HTTP GET 
            HttpGet request = new HttpGet("url?param1=value1"); 
            //【Step 3】设置HTTP参数,本例子是最简单地打开某个网址的HTTP GET,无需设置 
           //【Step 4】通过HttpClient来执行HTTP call(发出HTTP请求)  
            HttpResponse response = client.execute(request); 
            //【Step 5】处理HTTP响应,本例将整个响应的内容(HTTP 200消息的body)都在String中。 
            in = new BufferedReader( 
                    new InputStreamReader( 
                            response.getEntity().getContent())); 
            StringBuffer buff = new StringBuffer(""); 
            String line = ""; 
            String NL = System.getProperty("line.separator");  //实际上就是“\n”,可自动适配系统的换行符。 
            while((line = in.readLine()) != null ){ 
                buff.append(line + NL); 
            } 
            in.close();  
            Log.d("PRO",buff.toString());  
        }catch(Exception e){ 
            e.printStackTrace(); 
            Log.d("PRO",e.toString()); 
        }finally{ 
            if(in != null){ 
                try{ 
                    in.close(); //关闭BufferedReader,同时也关闭了底层的HTTP connection
                }catch(Exception e){ 
                    e.printStackTrace();  
                    Log.d("PRO","error in finally:\n" + e.toString()); 
                } 
            } 
        }         
    }  
    
}


HTTP POST方式

BufferedReader in = null; 
try{ 
    //【Step 1】创建一个HttpClient的对象(或使用已有的) 
    HttpClient client = new DefaultHttpClient(); 
    //【Step 2】实例化一个HTTP GET或者HTTP POST,本例是HTTP POST 
    HttpPost request = new HttpPost("url"); 
     
    //【Step 3】设置HTTP参数,本例根据抓包的内容填写,这是体力活,在完整HTTP服务的笔记后,会提供小例子下载。对于HTTP Post,需要传递键值对信息,从上面的转包可以看到,这部分不是作为request URI,而是作为HTML Form URL Encoded,为此我们需要用户元素为NameValuePair格式的list来存储这些信息,并封装在UrlEncodedFormEntiry对象中。通过setEntity()加入到请求对象中。
    List<NameValuePair> postParameters = new ArrayList<NameValuePair>();
    postParameters.add(new BasicNameValuePair("paraml","value1"));
    postParameters.add(new BasicNameValuePair("param2","value2"));      
    UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters);
    request.setEntity(formEntity); 
    
    //【Step 4】通过HttpClient来执行HTTP call(发出HTTP请求)
    HttpResponse response =client.execute(request); 
    
    //【Step 5】处理HTTP响应,本例将整个响应的内容(HTTP 200消息的body)都在String中。 
    in = new BufferedReader( 
            new InputStreamReader( 
                    response.getEntity().getContent())); 
    
    StringBuffer buff = new StringBuffer(""); 
    String line = ""; 
    String NL = System.getProperty("line.separator"); 
    while((line = in.readLine())!= null){ 
        buff.append(line + NL); 
    } 
    showInfo(buff.toString());     
}catch(Exception e){ 
    e.printStackTrace(); 
    showInfo(e.toString()); 
}finally{ 
    if(in != null){ 
        try{ 
            showInfo("== process in.colse() =="); 
            in.close(); 
        }catch(Exception e){ 
            e.printStackTrace(); 
            showInfo(e.toString()); 
        } 
    }    
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值