网络数据的处理之HttpClient

来源:互联网 发布:2017ipad视频软件 编辑:程序博客网 时间:2024/03/29 07:53
这一章我们主要来介绍网络数据的传递与处理,相信很多读者都希望做出来的应用能跟网络上的数据进行互动,如微博,论坛之类的,这里我们就要学习网络传输与返回数据的处理,首先网络传递参数有POST跟GET两种协议,做过网页或是学习过的同学应该知道.网页每个表单中都有一个<form action="XXX" method="post">参数,这里method就是提交表单参数使用的协议,当然,协议不止这两种,还有文件上传协议,这我们以后会讲,今天我们首来就来熟悉Android中对于POST跟GET协议的应用,首先我们提供了一个HttpConnectionUtil.java的辅助类,这里面对POST跟GET进行了封装
import java.io.BufferedReader;  
  1. import java.io.IOException;  
  2. import java.io.InputStreamReader;  
  3. import java.io.UnsupportedEncodingException;  
  4. import java.net.URLEncoder;  
  5. import java.util.ArrayList;  
  6. import java.util.List;  
  7. import java.util.Map;  
  8.   
  9. import org.apache.http.HttpResponse;  
  10. import org.apache.http.HttpStatus;  
  11. import org.apache.http.NameValuePair;  
  12. import org.apache.http.client.ClientProtocolException;  
  13. import org.apache.http.client.HttpClient;  
  14. import org.apache.http.client.entity.UrlEncodedFormEntity;  
  15. import org.apache.http.client.methods.HttpGet;  
  16. import org.apache.http.client.methods.HttpPost;  
  17. import org.apache.http.client.methods.HttpUriRequest;  
  18. import org.apache.http.impl.client.DefaultHttpClient;  
  19. import org.apache.http.message.BasicNameValuePair;  
  20.   
  21. import android.os.Handler;  
  22. import android.util.Log;  
  23.   
  24. public class HttpConnectionUtil  
  25.  
  26.     public static enum HttpMethod  
  27.      
  28.         GET, POST  
  29.      
  30.   
  31.       
  32.     public void asyncConnect(final String url, final HttpMethod method,  
  33.             final HttpConnectionCallback callback)  
  34.      
  35.         asyncConnect(url, nullmethod, callback);  
  36.      
  37.   
  38.       
  39.     public void syncConnect(final String url, final HttpMethod method,  
  40.             final HttpConnectionCallback callback)  
  41.      
  42.         syncConnect(url, nullmethod, callback);  
  43.      
  44.   
  45.       
  46.     public void asyncConnect(final String url,  
  47.             final Map<String, String> params, final HttpMethod method,  
  48.             final HttpConnectionCallback callback)  
  49.      
  50.         Handler handler new Handler();  
  51.         Runnable runnable new Runnable()  
  52.          
  53.             public void run()  
  54.              
  55.                 syncConnect(url, params, method, callback);  
  56.              
  57.         };  
  58.         handler.post(runnable);  
  59.      
  60.   
  61.       
  62.     public void syncConnect(final String url, final Map<String, String> params,  
  63.             final HttpMethod method, final HttpConnectionCallback callback)  
  64.      
  65.         String json null 
  66.         BufferedReader reader null 
  67.   
  68.         try  
  69.          
  70.             HttpClient client new DefaultHttpClient();  
  71.             HttpUriRequest request getRequest(url, params, method);  
  72.             HttpResponse response client.execute(request);  
  73.             if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK)  
  74.              
  75.                 reader new BufferedReader(new InputStreamReader(response  
  76.                         .getEntity().getContent()));  
  77.                 StringBuilder sb new StringBuilder();  
  78.                 for (String reader.readLine(); != nullreader  
  79.                         .readLine())  
  80.                  
  81.                     sb.append(s);  
  82.                  
  83.   
  84.                 json sb.toString();  
  85.              
  86.         catch (ClientProtocolException e)  
  87.          
  88.             Log.e("HttpConnectionUtil"e.getMessage(), e);  
  89.         catch (IOException e)  
  90.          
  91.             Log.e("HttpConnectionUtil"e.getMessage(), e);  
  92.         finally  
  93.          
  94.             try  
  95.              
  96.                 if (reader != null 
  97.                  
  98.                     reader.close();  
  99.                  
  100.             catch (IOException e)  
  101.              
  102.                 // ignore me   
  103.              
  104.          
  105.         callback.execute(json);  
  106.      
  107.   
  108.       
  109.     private HttpUriRequest getRequest(String url, Map<String, String> params,  
  110.             HttpMethod method)  
  111.      
  112.         if (method.equals(HttpMethod.POST))  
  113.          
  114.             List<NameValuePair> listParams new ArrayList<NameValuePair>();  
  115.             if (params != null 
  116.              
  117.                 for (String name params.keySet())  
  118.                  
  119.                     listParams.add(new BasicNameValuePair(name, params  
  120.                             .get(name)));  
  121.                  
  122.              
  123.             try  
  124.              
  125.                 UrlEncodedFormEntity entity new UrlEncodedFormEntity(  
  126.                         listParams);  
  127.                 HttpPost request new HttpPost(url);  
  128.                 request.setEntity(entity);  
  129.                 return request;  
  130.             catch (UnsupportedEncodingException e)  
  131.              
  132.                 // Should not come here, ignore me.   
  133.                 throw new java.lang.RuntimeException(e.getMessage(), e);  
  134.              
  135.         else  
  136.          
  137.             if (url.indexOf("?"0 
  138.              
  139.                 url += "?" 
  140.              
  141.             if (params != null 
  142.              
  143.                 for (String name params.keySet())  
  144.                  
  145.                     try  
  146.                      
  147.                         url += "&" name "="  
  148.                                 URLEncoder.encode(params.get(name), "UTF-8");  
  149.   
  150.                     catch (UnsupportedEncodingException e)  
  151.                      
  152.                         e.printStackTrace();  
  153.                      
  154.                  
  155.              
  156.             HttpGet request new HttpGet(url);  
  157.             return request;  
  158.          
  159.      
  160.       
  161.       
  162.     public interface HttpConnectionCallback  
  163.      
  164.           
  165.         void execute(String response);  
  166.      
  167.   
  168.  

这个类也是我从网上看到的,使用起来相当方便,希望读者能学会怎样使用,其实像java学习,可以将一些有用的类或是方法定义个自己包,将它们放进去,下次要用的话只要在主程序中调用就行了,这也是面向对象重要的方法.

这里面的方法,我就没有一行一行定义说明了,里面用的都是HttpClient的中方法

接下来,我们用这个类来进行Android的应用

main.xml(模板文件)

<?xml version="1.0" encoding="utf-8"?>  
  1. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  2.     android:orientation="vertical" android:layout_width="match_parent"  
  3.     android:layout_height="match_parent">  
  4.     <EditText android:layout_width="match_parent"  
  5.         android:layout_height="wrap_content" android:id="@+id/http_edit"  
  6.         android:text="http://">  
  7.         <requestFocus></requestFocus>  
  8.     </EditText>  
  9.     <RelativeLayout android:layout_width="match_parent"  
  10.         android:layout_height="wrap_content" android:id="@+id/relativeLayout1">  
  11.         <Button android:text="取消" android:layout_width="wrap_content"  
  12.             android:id="@+id/http_cancal" android:layout_height="wrap_content"  
  13.             android:layout_alignParentTop="true" android:layout_alignParentRight="true"></Button>  
  14.         <Button android:text="确定" android:layout_width="wrap_content"  
  15.             android:id="@+id/http_ok" android:layout_height="wrap_content"  
  16.             android:layout_alignParentTop="true" android:layout_toLeftOf="@+id/http_cancal"  
  17.             android:layout_marginRight="14dp"></Button>  
  18.     </RelativeLayout>  
  19.     <ScrollView android:layout_width="match_parent"  
  20.         android:layout_height="match_parent">  
  21.         <TextView android:id="@+id/http_text" android:text="TextView"  
  22.             android:textAppearance="?android:attr/textAppearanceSmall"  
  23.             android:layout_height="match_parent" android:layout_width="match_parent"></TextView>  
  24.     </ScrollView>  
  25.   
  26. </LinearLayout>  

然后就是主Actitiv的java代码了

import android.app.Activity;  
  1. import android.os.Bundle;  
  2. import android.text.Html;  
  3. import android.view.View;  
  4. import android.view.View.OnClickListener;  
  5. import android.widget.Button;  
  6. import android.widget.EditText;  
  7. import android.widget.TextView;  
  8.   
  9. import com.kang.http.HttpConnectionUtil;  
  10. import com.kang.http.HttpConnectionUtil.HttpConnectionCallback;  
  11. import com.kang.http.HttpConnectionUtil.HttpMethod;  
  12.   
  13. public class HttpClientDemo extends Activity  
  14.  
  15.     private Button ok_btn;  
  16.     private Button cancal_btn;  
  17.     private EditText edit_text;  
  18.     private TextView text;  
  19.   
  20.     @Override  
  21.     protected void onCreate(Bundle savedInstanceState)  
  22.      
  23.         // TODO Auto-generated method stub   
  24.         super.onCreate(savedInstanceState);  
  25.         setContentView(R.layout.http_client);  
  26.           
  27.         //确定按钮   
  28.         ok_btn (Button) findViewById(R.id.http_ok);  
  29.         ok_btn.setOnClickListener(new ClickEvent());  
  30.           
  31.         //取消按钮   
  32.         cancal_btn (Button) findViewById(R.id.http_cancal);  
  33.         cancal_btn.setOnClickListener(new ClickEvent());  
  34.           
  35.         //文本编辑框   
  36.         edit_text (EditText) findViewById(R.id.http_edit);  
  37.           
  38.         //文本框   
  39.         text (TextView) findViewById(R.id.http_text);  
  40.      
  41.       
  42.       
  43.     //自定义按钮点击方法   
  44.     public class ClickEvent implements OnClickListener  
  45.      
  46.   
  47.         @Override  
  48.         public void onClick(View v)  
  49.          
  50.             switch (v.getId())  
  51.              
  52.             case R.id.http_ok:  
  53.                 //网址   
  54.                 String url edit_text.getText().toString().trim();  
  55.                   
  56.                 if (!url.equals("http://"&& !url.equals(""))  
  57.                  
  58.                     //自定义类,封装了GET/POST方法,而且同样也封装了同步跟异步的方法   
  59.                     HttpConnectionUtil conn new HttpConnectionUtil();  
  60.                     conn.asyncConnect(url, HttpMethod.GET,  
  61.                             new HttpConnectionCallback()  
  62.                              
  63.   
  64.                                 @Override  
  65.                                 public void execute(String response)  
  66.                                  
  67.                                     text.setText(Html.fromHtml(response));  
  68.                                  
  69.                             });  
  70.                  
  71.   
  72.                 break 
  73.   
  74.             case R.id.http_cancal:  
  75.                 edit_text.setText("http://");  
  76.   
  77.                 break 
  78.   
  79.              
  80.   
  81.          
  82.   
  83.      
  84.  

看里面 ClickEvent类中onClick方法中我们就使用了自定义的HttpConnectionUtil类,别急着运行了,接下来还有一步,也是最重要的,就是权限的增加,你要访问网络,肯定需要访问网络的权限,在AndroidManifest.xml中加入<uses-permission android:name="android.permission.INTERNET"></uses-permission>这一句,至于加哪里,那你可别问我了,百度或是google一下吧,呵呵,卖卖关子,现在就可以运行了,看图是不是跟我的一样

你一定会奇怪,怎么会有其他一些代码呢?呵呵,这里我们取出的是它的源代码.OK,这一章讲完了,下一章我们就要来实现Mysql数据库+PHP+Android的显示了,相信这会是很多读者感兴趣的一章,谢谢

原创粉丝点击