zoukankan      html  css  js  c++  java
  • 2.腾讯微博Android客户端开发——Parameter类和SyncHttp类编写 .

    在上一节介绍的OAuth认证过程中我们可以看到我们需要不断地和腾讯微博开放平台进行数据的交互,因此我们需要编写一个类用来发送Http请求,并且能处理平台返回过来的数据。学习Html的朋友应该知道Get和Post两种方式提交数据,在这里我们同样也需要编写Post和Get两个方法模拟Post和Get请求。在发送微博时我们还可以上传照片,所以我们还应编写一个方法用于上传图片,但是在这里暂时还不编写上传数据的方法。另外在模拟Http请求时我们需要传递参数,因此我们需创建一个Parameter类,表示参数对象。在腾讯微博开放平台中关于oauth_signature参数值的产生过程介绍中有这样一幅描述图(http://open.t.qq.com/resource.php?i=1,2#tag0 )

    我们可以看到参数对象是需要进行排序的,这里的排序是参数按name进行字典升序排列,详细介绍我们可以参考这篇介绍:http://wiki.opensns.qq.com/wiki/%E3%80%90QQ%E7%99%BB%E5%BD%95%E3%80%91%E7%AD%BE%E5%90%8D%E5%8F%82%E6%95%B0oauth_signature%E7%9A%84%E8%AF%B4%E6%98%8E。因此我们需让我们的Parameter类实现 Comparable<T>接口,重写里面的方法,最终Parameter类代码如下: 

    1. package com.szy.weibo.model;  
    2. import java.io.Serializable;  
    3. /** 
    4.  *@author coolszy 
    5.  *@date 2011-5-29 
    6.  *@blog http://blog.csdn.net/coolszy 
    7.  */  
    8. public class Parameter implements Serializable, Comparable<Parameter>   
    9. {  
    10.     private static final long serialVersionUID = 2721340807561333705L;  
    11.       
    12.     private String name;//参数名   
    13.     private String value;//参数值   
    14.   
    15.     public Parameter()  
    16.     {  
    17.         super();  
    18.     }  
    19.   
    20.     public Parameter(String name, String value)  
    21.     {  
    22.         super();  
    23.         this.name = name;  
    24.         this.value = value;  
    25.     }  
    26.   
    27.     public String getName()  
    28.     {  
    29.         return name;  
    30.     }  
    31.   
    32.     public void setName(String name)  
    33.     {  
    34.         this.name = name;  
    35.     }  
    36.   
    37.     public String getValue()  
    38.     {  
    39.         return value;  
    40.     }  
    41.   
    42.     public void setValue(String value)  
    43.     {  
    44.         this.value = value;  
    45.     }  
    46.   
    47.     @Override  
    48.     public String toString()  
    49.     {  
    50.         return "Parameter [name=" + name + ", value=" + value + "]";  
    51.     }  
    52.   
    53.     @Override  
    54.     public boolean equals(Object arg0)  
    55.     {  
    56.         if (null == arg0)  
    57.         {  
    58.             return false;  
    59.         }  
    60.         if (this == arg0)  
    61.         {  
    62.             return true;  
    63.         }  
    64.         if (arg0 instanceof Parameter)  
    65.         {  
    66.             Parameter param = (Parameter) arg0;  
    67.   
    68.             return this.getName().equals(param.getName()) && this.getValue().equals(param.getValue());  
    69.         }  
    70.         return false;  
    71.     }  
    72.   
    73.     @Override  
    74.     public int compareTo(Parameter param)  
    75.     {  
    76.         int compared;  
    77.         compared = name.compareTo(param.getName());  
    78.         if (0 == compared)  
    79.         {  
    80.             compared = value.compareTo(param.getValue());  
    81.         }  
    82.         return compared;  
    83.     }  
    84. }  

         模拟发送Http请求我们可以使用HttpURLConnection类进行操作,但是Android平台集成了功能强大且编写更容易的commons-httpclient.jar,因此在这里介绍如何通过commons-httpclient进行Http请求。发送Http请求可以有两种方式:一种是同步,一种是异步。由于我对异步不是很熟悉,所以这里先提供同步方式发送Http请求:

    1. package com.szy.weibo.service;  
    2.   
    3. import java.io.ByteArrayOutputStream;  
    4. import java.io.IOException;  
    5. import java.io.InputStream;  
    6. import java.util.List;  
    7.   
    8. import org.apache.commons.httpclient.HttpClient;  
    9. import org.apache.commons.httpclient.HttpStatus;  
    10. import org.apache.commons.httpclient.NameValuePair;  
    11. import org.apache.commons.httpclient.methods.GetMethod;  
    12. import org.apache.commons.httpclient.methods.PostMethod;  
    13. import org.apache.commons.httpclient.params.HttpMethodParams;  
    14. import org.apache.commons.logging.Log;  
    15. import org.apache.commons.logging.LogFactory;  
    16.   
    17. import com.szy.weibo.model.Parameter;  
    18.   
    19. /** 
    20.  *@author coolszy 
    21.  *@date 2011-5-29 
    22.  *@blog http://blog.csdn.net/coolszy 
    23.  */  
    24.   
    25. /** 
    26.  * 以同步方式发送Http请求 
    27.  */  
    28. public class SyncHttp  
    29. {  
    30.     private static final Log LOG = LogFactory.getLog(SyncHttp.class);  
    31.       
    32.     private static final int CONNECTION_TIMEOUT = 1000 * 5// Http连接超时时间   
    33.   
    34.     /** 
    35.      * 通过GET方式发送请求 
    36.      * @param url URL地址 
    37.      * @param params 参数 
    38.      * @return  
    39.      * @throws Exception 
    40.      */  
    41.     public String httpGet(String url, String params) throws Exception  
    42.     {  
    43.         String response = null//返回信息   
    44.         if (null!=params&&!params.equals(""))  
    45.         {  
    46.             url += "?" + params;  
    47.         }  
    48.         // 构造HttpClient的实例   
    49.         HttpClient httpClient = new HttpClient();  
    50.         // 创建GET方法的实例   
    51.         GetMethod httpGet = new GetMethod(url);  
    52.         // 设置超时时间   
    53.         httpGet.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, new Integer(CONNECTION_TIMEOUT));  
    54.         try  
    55.         {  
    56.             int statusCode = httpClient.executeMethod(httpGet);  
    57.             if (statusCode == HttpStatus.SC_OK) //SC_OK = 200   
    58.             {  
    59.                 InputStream inputStream = httpGet.getResponseBodyAsStream(); //获取输出流,流中包含服务器返回信息   
    60.                 response = getData(inputStream);//获取返回信息   
    61.             }  
    62.             else  
    63.             {  
    64.                 LOG.debug("Get Method Statuscode : "+statusCode);  
    65.             }  
    66.         } catch (Exception e)  
    67.         {  
    68.             throw new Exception(e);  
    69.         } finally  
    70.         {  
    71.             httpGet.releaseConnection();  
    72.             httpClient = null;  
    73.         }  
    74.         return response;  
    75.     }  
    76.   
    77.     /** 
    78.      * 通过POST方式发送请求 
    79.      * @param url URL地址 
    80.      * @param params 参数 
    81.      * @return 
    82.      * @throws Exception 
    83.      */  
    84.     public String httpPost(String url, List<Parameter> params) throws Exception  
    85.     {  
    86.         String response = null;  
    87.         HttpClient httpClient = new HttpClient();  
    88.         PostMethod httpPost = new PostMethod(url);  
    89.         //Post方式我们需要配置参数   
    90.         httpPost.addParameter("Connection""Keep-Alive");  
    91.         httpPost.addParameter("Charset""UTF-8");  
    92.         httpPost.addParameter("Content-Type""application/x-www-form-urlencoded");  
    93.         httpPost.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, new Integer(CONNECTION_TIMEOUT));  
    94.         if (null!=params&¶ms.size()!=0)  
    95.         {  
    96.             //设置需要传递的参数,NameValuePair[]   
    97.             httpPost.setRequestBody(buildNameValuePair(params));  
    98.         }  
    99.         try  
    100.         {  
    101.             int statusCode = httpClient.executeMethod(httpPost);  
    102.             if (statusCode == HttpStatus.SC_OK)  
    103.             {  
    104.                 InputStream inputStream = httpPost.getResponseBodyAsStream();  
    105.                 response = getData(inputStream);  
    106.             }  
    107.             else  
    108.             {  
    109.                 LOG.debug("Post Method Statuscode : "+statusCode);  
    110.             }  
    111.         } catch (Exception e)  
    112.         {  
    113.             throw new Exception(e);  
    114.         } finally  
    115.         {  
    116.             httpPost.releaseConnection();  
    117.             httpClient = null;  
    118.         }  
    119.         return response;  
    120.     }  
    121.       
    122.     /** 
    123.      * 构建NameValuePair数组 
    124.      * @param params List<Parameter>集合 
    125.      * @return 
    126.      */  
    127.     private NameValuePair[] buildNameValuePair(List<Parameter> params)  
    128.     {  
    129.         int size = params.size();  
    130.         NameValuePair[] pair = new NameValuePair[size];  
    131.         for(int i = 0 ;i<size;i++)  
    132.         {  
    133.             Parameter param = params.get(i);  
    134.             pair[i] = new NameValuePair(param.getName(),param.getValue());  
    135.         }  
    136.         return pair;  
    137.     }  
    138.     /** 
    139.      * 从输入流获取信息 
    140.      * @param inputStream 输入流 
    141.      * @return 
    142.      * @throws Exception 
    143.      */  
    144.     private String getData(InputStream inputStream) throws Exception  
    145.     {  
    146.         String data = "";  
    147.         //内存缓冲区   
    148.         ByteArrayOutputStream outputStream = new ByteArrayOutputStream();  
    149.         int len = -1;  
    150.         byte[] buff = new byte[1024];  
    151.         try  
    152.         {  
    153.             while((len=inputStream.read(buff))!=-1)  
    154.             {  
    155.                 outputStream.write(buff, 0, len);  
    156.             }  
    157.             byte[] bytes = outputStream.toByteArray();  
    158.             data = new String(bytes);  
    159.         } catch (IOException e)  
    160.         {  
    161.             throw new Exception(e.getMessage(),e);  
    162.         }  
    163.         finally  
    164.         {  
    165.             outputStream.close();  
    166.         }  
    167.         return data;  
    168.     }  
    169. }    

     本节课程下载地址:http://u.115.com/file/aq8oydql

     本节课程文档下载:http://download.csdn.net/source/3405206

    原文:http://blog.csdn.net/coolszy/article/details/6525966

  • 相关阅读:
    poj3180 The Cow Prom
    洛谷P1434 滑雪
    洛谷P1199 三国游戏
    洛谷P1230 智力大冲浪
    洛谷P1012 拼数
    洛谷P1106 删数问题
    bzoj3538 [Usaco2014 Open]Dueling GPS
    Android(java)学习笔记134:Android数据存储5种方式总结
    Android(java)学习笔记133:Eclipse中的控制台不停报错Can't bind to local 8700 for debugger
    Android(java)学习笔记132:eclipse 导入项目是提示:某些项目因位于工作空间目录中而被隐藏。
  • 原文地址:https://www.cnblogs.com/xiaoxiaoboke/p/2116217.html
Copyright © 2011-2022 走看看