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

被折叠的 条评论
为什么被折叠?



