码迷,mamicode.com
首页 > 其他好文 > 详细

HttpClient初步

时间:2014-09-10 22:19:51      阅读:314      评论:0      收藏:0      [点我收藏+]

标签:des   cWeb   style   blog   http   color   io   os   使用   

1. HttpClient库的基础知识介绍

2. 使用HttpClient向服务器发送请求

3. 接收从服务器端返回的响应

 

1. HttpClient库的基础知识介绍

  bubuko.com,布布扣

 

2. 使用HttpClient向服务器发送请求

  bubuko.com,布布扣

  前备知识:

    面向对象中一切都是对象!!!!!!!!!!

    主线程决不能访问服务器!!!!!!!!!!

    Http服务器发还客户端响应码, 如果是200即正常. 404表示客户端错误, 505服务器端错误

    访问服务器地址用marsChen网站测试用的地址

      bubuko.com,布布扣

 1 public static class PlaceholderFragment extends Fragment {
 2         
 3         private Button button;
 4 
 5         public PlaceholderFragment() {
 6         }
 7 
 8         @Override
 9         public View onCreateView(LayoutInflater inflater, ViewGroup container,
10                 Bundle savedInstanceState) {
11             View rootView = inflater.inflate(R.layout.fragment_main, container, false);
12             
13             button = (Button)rootView.findViewById(R.id.buttonId);
14             button.setOnClickListener(new OnClickListener() {                
15                 public void onClick(View v) {
16                     NetworkThread nt = new NetworkThread();
17                     nt.start();
18                 }
19             });
20             
21             return rootView;
22         }
23         
24         class NetworkThread extends Thread{  //主线程不能访问网路!!!
25             @Override
26             public void run() {
27                 //创建HttpClient
28                 HttpClient httpClient = new DefaultHttpClient();
29                 //创建代表请求的对象,参数是访问的服务地址
30                 //如Baidu就是http://www.baidu.com
31                 HttpGet httpGet = new HttpGet("http://www.marschen.com/data1/html");
32                 try {
33                     //执行请求, 获取服务器发还的相应对象
34                     HttpResponse resp = httpClient.execute(httpGet);
35                     //检查相应的状态是否正常, 检查状态码是否是200
36                     int code = resp.getStatusLine().getStatusCode();
37                     if(code == 200){
38                         //从相应对象中取值,得到的是流对象
39                         HttpEntity entity = resp.getEntity();
40                         InputStream in = entity.getContent();
41                         BufferedReader reader = new BufferedReader(new InputStreamReader(in));
42                         String line = reader.readLine();
43                         Log.i("tag","Got From Server: " + line);
44                     }
45                 } 
46                 catch (IOException e) {
47                     // TODO Auto-generated catch block
48                     e.printStackTrace();
49                 }
50             }           
51         }
52     }

 

  

HttpClient初步

标签:des   cWeb   style   blog   http   color   io   os   使用   

原文地址:http://www.cnblogs.com/iMirror/p/3965166.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!