天天看点

Android HttpClient基本使用方法

这里只介绍如何使用httpclient发起get或者post请求

get 方式

java代码  

Android HttpClient基本使用方法

//先将参数放入list,再对参数进行url编码  

list<basicnamevaluepair> params = new linkedlist<basicnamevaluepair>();  

params.add(new basicnamevaluepair("param1", "中国"));  

params.add(new basicnamevaluepair("param2", "value2"));  

//对参数编码  

string param = urlencodedutils.format(params, "utf-8");  

//baseurl             

string baseurl = "http://ubs.free4lab.com/php/method.php";  

//将url与参数拼接  

httpget getmethod = new httpget(baseurl + "?" + param);  

httpclient httpclient = new defaulthttpclient();  

try {  

    httpresponse response = httpclient.execute(getmethod); //发起get请求  

    log.i(tag, "rescode = " + response.getstatusline().getstatuscode()); //获取响应码  

    log.i(tag, "result = " + entityutils.tostring(response.getentity(), "utf-8"));//获取服务器响应内容  

} catch (clientprotocolexception e) {  

    // todo auto-generated catch block  

    e.printstacktrace();  

} catch (ioexception e) {  

}  

post方式

Android HttpClient基本使用方法

//和get方式一样,先将参数放入list  

params = new linkedlist<basicnamevaluepair>();  

params.add(new basicnamevaluepair("param1", "post方法"));  

params.add(new basicnamevaluepair("param2", "第二个参数"));  

    httppost postmethod = new httppost(baseurl);  

    postmethod.setentity(new urlencodedformentity(params, "utf-8")); //将参数填入post entity中  

    httpresponse response = httpclient.execute(postmethod); //执行post方法  

    log.i(tag, "result = " + entityutils.tostring(response.getentity(), "utf-8")); //获取响应内容  

} catch (unsupportedencodingexception e) {  

}