HttpClient初步
1. HttpClient库的基础知识介绍
2. 使用HttpClient向服务器发送请求
3. 接收从服务器端返回的响应
1. HttpClient库的基础知识介绍
2. 使用HttpClient向服务器发送请求
前备知识:
面向对象中一切都是对象!!!!!!!!!!
主线程决不能访问服务器!!!!!!!!!!
Http服务器发还客户端响应码, 如果是200即正常. 404表示客户端错误, 505服务器端错误
访问服务器地址用marsChen网站测试用的地址
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 }
还需要添加申请权限, 在AndroidMenifest.xml中, 添加 <uses-permission android:name = "android.permission.INTERNET"/>
运行结果: