代码改变世界

android 网络通信 方案1 httpclient

2012-01-09 14:31  cjzhang  阅读(283)  评论(0编辑  收藏  举报

 

apace httpclient为客户端编程提供高效、功能丰富的工具包支持。

 

 1 try{
2
3 HttpClient hc=new DefaultHttpClient();
4
5 HttpGet get=new HttpGet("http://www.google.com");
6
7 HttpResponse rp=hc.execute(get);
8
9 if(rp.getStatusLine().getStatus()==HttpStatus.SC_OK)
10
11 {
12
13 ........//处理数据
14
15 }
16
17 catch(IOException e){
18
19 ...
20
21 }


 1 public class LearnActivity extends Activity {
2 /** Called when the activity is first created. */
3 @Override
4 public void onCreate(Bundle savedInstanceState) {
5 super.onCreate(savedInstanceState);
6 setContentView(R.layout.main);
7
8 TextView tv=(TextView)findViewById(R.id.hello);
9
10 String httpurl="www.baidu.com";
11 //实例化http请求,httppost
12 HttpPost httprequest=new HttpPost(httpurl);
13
14 //用NameValuePair 来保存要传递的post参数
15 List<NameValuePair> params=new ArrayList<NameValuePair>();
16 params.add(new BasicNameValuePair("par","HttpClient"));
17 try
18 {
19 //设置字符串
20 HttpEntity httpentity =new UrlEncodedFormEntity(params,"gb2312");
21 //设置请求httpresquest的编码
22 httprequest.setEntity(httpentity);
23 //取得默认的httpclient
24 HttpClient httpclient=new DefaultHttpClient();
25 //执行http连接
26 HttpResponse httpresponse=httpclient.execute(httprequest);
27 if(httpresponse.getStatusLine().getStatusCode()==HttpStatus.SC_OK)
28 {
29 String strresult=EntityUtils.toString(httpresponse.getEntity());
30 tv.setText(strresult);
31 }
32 else{
33 tv.setText("come on ,baby!");
34 }
35 }
36 catch(ClientProtocolException e)
37 {
38 tv.setText(e.getMessage().toString());
39 }
40 catch (IOException e) {
41 tv.setText(e.getMessage().toString());
42 }
43 catch (Exception e) {
44 tv.setText(e.getMessage().toString());
45 }
46
47 }
48 }




47
48
49
50
51 public void onCreate(Bundle savedInstanceState) {
52 super.onCreate(savedInstanceState);
53 setContentView(R.layout.main);
54
55 TextView tv = (TextView) findViewById(R.id.hello);
56 //url地址
57 String httpurl = "www.baidu.com";
58 //实例化http请求类型: httpget
59 HttpGet httpRequest=new HttpGet(httpurl);
60
61 try{
62 //实例化httpclient对象
63 HttpClient httpclient=new DefaultHttpClient();
64 //通过Httpclient执行请求
65 HttpResponse httpResponse=httpclient.execute(httpRequest);
66 //判断请求成功与否
67 if(httpResponse.getStatusLine().getStatusCode()== HttpStatus.SC_OK){
68 String strResult=EntityUtils.toString(httpResponse.getEntity());
69 tv.setText(strResult);
70 }
71 else
72 {
73 tv.setText("come on ,girls");
74 }
75
76 }
77 catch(ClientProtocolException e)
78 {
79 tv.setText(e.getMessage().toString());
80 }
81 catch (IOException e) {
82 tv.setText(e.getMessage().toString());
83 }
84 catch (Exception e) {
85 tv.setText(e.getMessage().toString());
86 }
87
88 }