Android客户端使用HttpClient发起web数据访问

      HttpClient与服务器数据交互方式:HttpPost和HttpGet 分别对应Post和Get提交。因为要做Android客户端的缘故,所以就必须实现客户端与服务器实现数据交互,以保证数据链条的通畅,实现数据闭环。由于之前对Android客户端访问web数据没有设置权限,所以可以很好的访问系统资源,但是如果是开发应用这种方式就存在极大的安全隐患,一个Host或Get提交过去数据就获取到了,web端系统完全就是裸奔。所以web端权限管理很有必要,也就不用过于担心Android客户端带来的安全隐患。Android新手学习一般都会遇到问题,前两天就遇到web端设置了权限而Android客户端发起访问获取不到数据的问题。

1.HttpPost与HttpGet实现用户登录和列表展现

编写一个测试Activity,MainActivity.

  1. package com.boonya.httpclienttest;  
  2.   
  3. import java.io.BufferedReader;  
  4. import java.io.IOException;  
  5. import java.io.InputStreamReader;  
  6. import java.io.UnsupportedEncodingException;  
  7. import java.util.ArrayList;  
  8. import java.util.HashMap;  
  9. import java.util.List;  
  10. import org.apache.http.HttpResponse;  
  11. import org.apache.http.client.ClientProtocolException;  
  12. import org.apache.http.client.HttpClient;  
  13. import org.apache.http.client.entity.UrlEncodedFormEntity;  
  14. import org.apache.http.client.methods.HttpGet;  
  15. import org.apache.http.client.methods.HttpPost;  
  16. import org.apache.http.message.BasicNameValuePair;  
  17. import org.apache.http.protocol.HTTP;  
  18. import org.json.JSONArray;  
  19. import org.json.JSONObject;  
  20. import com.boonya.httpclienttest.utils.HtttpClientUtil;  
  21. import android.app.Activity;  
  22. import android.os.Bundle;  
  23. import android.util.Log;  
  24. import android.widget.ListView;  
  25. import android.widget.SimpleAdapter;  
  26. import android.widget.Toast;  
  27.   
  28. public class MainActivity extends Activity  
  29. {  
  30.   
  31.     private static final String TAG = "MainActivity";  
  32.   
  33.     private List<HashMap<String, Object>> videos = null;  
  34.   
  35.     private HashMap<String, Object> video = null;  
  36.   
  37.     private ListView listView = null;  
  38.       
  39.     private static String loginurl = "http://192.168.1.147:8090/wtms/androidservice/login";  
  40.       
  41.     private static String getdataurl = "http://192.168.1.147:8090/wtms/androidservice/videos.avd";  
  42.   
  43.     @Override  
  44.     public void onCreate(Bundle savedInstanceState)  
  45.     {  
  46.         super.onCreate(savedInstanceState);  
  47.         setContentView(R.layout.main);  
  48.   
  49.         listView = (ListView) findViewById(R.id.videos);  
  50.           
  51.         postMethod();  
  52.   
  53.         getMethod();  
  54.     }  
  55.   
  56.     /** 
  57.      * HttpGet获取服务器数据显示 
  58.      *  
  59.      * @param url 
  60.      */  
  61.     protected void getMethod()  
  62.     {  
  63.         HttpGet request = new HttpGet(getdataurl);    
  64.         //request.setHeader("Cookie", HtttpClientUtil.getCookie());//设置cookie   
  65.         try  
  66.         {  
  67.             //设置请求参数项    
  68.             //request.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));    
  69.             HttpClient client = HtttpClientUtil.getInstance();    
  70.             //执行请求返回相应    
  71.             HttpResponse response = client.execute(request);  
  72.             // 判断请求是否成功  
  73.             if (response.getStatusLine().getStatusCode() == 200)  
  74.             { // 200表示请求成功  
  75.   
  76.                 StringBuilder builder = new StringBuilder();  
  77.                 BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));  
  78.   
  79.                 String s = null;  
  80.                 while ((s = bufferedReader.readLine()) != null)  
  81.                 {  
  82.                     builder.append(s);  
  83.                 }  
  84.   
  85.                 // String out = EntityUtils.toString(entity, "UTF-8");  
  86.                 String msg = builder.toString();  
  87.                   
  88.                 Log.d("log"">>>>执行 方法 getMethod()获取到范围值:"+msg);  
  89.   
  90.                 JSONArray jsonArray = new JSONArray(msg);  
  91.   
  92.                 videos = new ArrayList<HashMap<String, Object>>();  
  93.                 for (int i = 0; i < jsonArray.length(); i++)  
  94.                 {  
  95.                     JSONObject jsonObject = (JSONObject) jsonArray.get(i);  
  96.                     int id = jsonObject.getInt("id");  
  97.                     String name = jsonObject.getString("name");  
  98.                     int timelength = jsonObject.getInt("time");  
  99.   
  100.                     video = new HashMap<String, Object>();  
  101.                     video.put("id", id);  
  102.                     video.put("name", name);  
  103.                     video.put("timelength""时长为:" + timelength);  
  104.   
  105.                     videos.add(video);  
  106.                 }  
  107.   
  108.                 SimpleAdapter adapter = new SimpleAdapter(this, videos, R.layout.item, new String[]  
  109.                 { "name""timelength" }, new int[]  
  110.                 { R.id.title, R.id.timelength });  
  111.                 listView.setAdapter(adapter);  
  112.   
  113.             }  
  114.         } catch (Exception e)  
  115.         {  
  116.             e.printStackTrace();  
  117.             Log.e(TAG, e.toString());  
  118.             Toast.makeText(MainActivity.this"获取数据失败", Toast.LENGTH_LONG).show();  
  119.         }  
  120.     }  
  121.   
  122.     /** 
  123.      * HttpPost提交数据 
  124.      */  
  125.     @SuppressWarnings(  
  126.     { "unchecked""rawtypes" })  
  127.     protected void postMethod()  
  128.     {  
  129.   
  130.         try  
  131.         {  
  132.             // 使用ApacheHttp客户端进行连接(重要方法)  
  133.             HttpClient client = HtttpClientUtil.getInstance();  
  134.   
  135.             // 如果是Get提交则创建HttpGet对象,否则创建HttpPost对象  
  136.             // POST提交的方式  
  137.             HttpPost request = new HttpPost(loginurl);  
  138.             // 如果是Post提交可以将参数封装到集合中传递  
  139.             List params = new ArrayList();  
  140.             params.add(new BasicNameValuePair("username""test"));  
  141.             params.add(new BasicNameValuePair("password""test"));  
  142.             // UrlEncodedFormEntity用于将集合转换为Entity对象  
  143.             request.setEntity(new UrlEncodedFormEntity(params,HTTP.UTF_8));  
  144.             try  
  145.             {  
  146.                 // 获取相应消息  
  147.                 HttpResponse response = client.execute(request);  
  148.                 StringBuilder builder = new StringBuilder();   
  149.                 BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));   
  150.                 // 操作cookie  
  151.                /* List<Cookie> cookies = ((AbstractHttpClient) client).getCookieStore().getCookies(); 
  152.                 if(cookies!=null&&cookies.size()>0) 
  153.                 { 
  154.                     for (int i = 0; i < cookies.size(); i++) 
  155.                     { 
  156.                         HtttpClientUtil.setCookie(cookies.get(i).getValue()); 
  157.                     } 
  158.                 }*/  
  159.                 String s =null;  
  160.                 while((s = bufferedReader.readLine())!=null){  
  161.                     builder.append(s);   
  162.                 }  
  163.                   
  164.                 String string=builder.toString();  
  165.                 Log.d("log"">>>>执行 方法 postMethod()获取到范围值:"+string);  
  166.                   
  167.             } catch (ClientProtocolException e)  
  168.             {  
  169.                 e.printStackTrace();  
  170.             } catch (IOException e)  
  171.             {  
  172.                 e.printStackTrace();  
  173.             }  
  174.   
  175.         } catch (UnsupportedEncodingException e)  
  176.         {  
  177.             e.printStackTrace();  
  178.         }  
  179.   
  180.     }  
  181.       
  182. }  

2.实现客户端与服务器cookie共享

      这里采用单例模式实现HttpClient对象在Android客户端的唯一性,用户在登录系统后,这个对象会记录用户的Cookie,一旦建立客户端与服务器的访问认证,以后就可以任意发送HTTP请求到服务器请求或操作资源了。

  1. package com.boonya.httpclienttest.utils;  
  2.   
  3. import org.apache.http.client.HttpClient;  
  4. import org.apache.http.impl.client.DefaultHttpClient;  
  5. import org.apache.http.params.BasicHttpParams;  
  6. import org.apache.http.params.HttpConnectionParams;  
  7.   
  8. public class HtttpClientUtil  
  9. {  
  10.     /** 设置请求超时10秒钟 */  
  11.     private static final int REQUEST_TIMEOUT = 10 * 1000;  
  12.       
  13.     /** 设置等待数据超时时间10秒钟 */  
  14.     private static final int SO_TIMEOUT = 10 * 1000;  
  15.   
  16.     private static HttpClient instance;  
  17.       
  18.     /**  记住cookie字符串*/  
  19.     private static String cookie;  
  20.   
  21.     /** 
  22.      * 自定义方法:初始化HttpClient,并设置超时 
  23.      *  
  24.      * @return 返回:HttpClient 对象 
  25.      */  
  26.     private HtttpClientUtil()  
  27.     {  
  28.   
  29.     }  
  30.       
  31.     public static String getCookie()  
  32.     {  
  33.         return cookie;  
  34.     }  
  35.   
  36.   
  37.   
  38.     public static void setCookie(String cookie)  
  39.     {  
  40.         HtttpClientUtil.cookie = cookie;  
  41.     }  
  42.   
  43.   
  44.   
  45.     public static HttpClient getInstance()  
  46.     {  
  47.         if (instance == null)  
  48.         {  
  49.             BasicHttpParams httpParams = new BasicHttpParams();  
  50.   
  51.             HttpConnectionParams.setConnectionTimeout(httpParams, REQUEST_TIMEOUT);  
  52.   
  53.             HttpConnectionParams.setSoTimeout(httpParams, SO_TIMEOUT);  
  54.   
  55.             instance = new DefaultHttpClient(httpParams);  
  56.         }  
  57.         return instance;  
  58.     }  
  59.   
  60. }  
上面cookie字段并非必须的,如果HttpClient不是单例的,那么用户需要在静态变量来记住登录后的cookie。

优化HttpClientUtil的cookie获取方法:

  1. package com.boonya.httpclienttest.utils;  
  2.   
  3. import java.util.List;  
  4.   
  5. import org.apache.http.client.HttpClient;  
  6. import org.apache.http.cookie.Cookie;  
  7. import org.apache.http.impl.client.AbstractHttpClient;  
  8. import org.apache.http.impl.client.DefaultHttpClient;  
  9. import org.apache.http.params.BasicHttpParams;  
  10. import org.apache.http.params.HttpConnectionParams;  
  11.   
  12. public class HtttpClientUtil  
  13. {  
  14.     /** 设置请求超时10秒钟 */  
  15.     private static final int REQUEST_TIMEOUT = 10 * 1000;  
  16.   
  17.     /** 设置等待数据超时时间10秒钟 */  
  18.     private static final int SO_TIMEOUT = 10 * 1000;  
  19.   
  20.     private static HttpClient instance;  
  21.   
  22.     /** 记住cookie字符串 */  
  23.     private static String cookie = null;  
  24.   
  25.     /** 
  26.      * 自定义方法:初始化HttpClient,并设置超时 
  27.      *  
  28.      * @return 返回:HttpClient 对象 
  29.      */  
  30.     private HtttpClientUtil()  
  31.     {  
  32.   
  33.     }  
  34.   
  35.     public static String getCookie()  
  36.     {  
  37.         // 确保实例存在  
  38.         HtttpClientUtil.getInstance();  
  39.         // 获取cookie  
  40.         List<Cookie> cookies = ((AbstractHttpClient) instance).getCookieStore().getCookies();  
  41.         if (cookies != null && cookies.size() > 0)  
  42.         {  
  43.             for (int i = 0; i < cookies.size(); i++)  
  44.             {  
  45.                 cookie = cookies.get(i).getValue();  
  46.             }  
  47.         }  
  48.         return cookie;  
  49.     }  
  50.   
  51.     public static HttpClient getInstance()  
  52.     {  
  53.         if (instance == null)  
  54.         {  
  55.             BasicHttpParams httpParams = new BasicHttpParams();  
  56.   
  57.             HttpConnectionParams.setConnectionTimeout(httpParams, REQUEST_TIMEOUT);  
  58.   
  59.             HttpConnectionParams.setSoTimeout(httpParams, SO_TIMEOUT);  
  60.   
  61.             instance = new DefaultHttpClient(httpParams);  
  62.         }  
  63.         return instance;  
  64.     }  
  65.   
  66. }  

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值