ANDROID_MARS学习笔记_S04_007_从服务器获取微博数据时间线

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ANDROID_MARS学习笔记_S04_007_从服务器获取微博数据时间线相关的知识,希望对你有一定的参考价值。

、代码

1.xml
(1)activity_main.xml

 1 <?xml version="1.0" encoding="utf-8"?>
 2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 3     android:orientation="vertical"
 4     android:layout_width="fill_parent"
 5     android:layout_height="fill_parent"
 6     >
 7         <Button android:id="@+id/btn_launch_oauth"
 8                 android:layout_width="fill_parent"
 9                 android:layout_height="wrap_content"
10                 android:text="Launch OAuth Flow"/>
11 
12         <Button 
13                 android:id="@+id/btn_sendWeiBo"
14                 android:layout_width="fill_parent"
15                 android:layout_height="wrap_content"
16                 android:text="发送一条微博消息"
17         />
18         <Button 
19                 android:id="@+id/btn_getWeiBoList"
20                 android:layout_width="fill_parent"
21                 android:layout_height="wrap_content"
22                 android:text="得到主页时间线数据"
23         />
24 </LinearLayout>

 

(2)AndroidManifest.xml

 1 <?xml version="1.0" encoding="utf-8"?>
 2 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
 3       package="org.marsdroid.oauth04"
 4       android:versionCode="1"
 5       android:versionName="1.0">
 6     <uses-sdk android:minSdkVersion="10" />
 7     <uses-permission android:name="android.permission.INTERNET" />
 8     <application android:icon="@drawable/icon" android:label="@string/app_name">
 9         <activity android:name=".MainActivity" android:label="@string/app_name">
10             <intent-filter>
11                 <action android:name="android.intent.action.MAIN" />
12                 <category android:name="android.intent.category.LAUNCHER" />
13             </intent-filter>
14         </activity>
15         <activity android:name=".PrepareRequestTokenActivity" android:launchMode="singleTask">
16             <intent-filter>
17                 <action android:name="android.intent.action.VIEW" />
18                 <category android:name="android.intent.category.DEFAULT" />
19                 <category android:name="android.intent.category.BROWSABLE" />
20                 <data android:scheme="x-oauthflow" android:host="callback" />
21             </intent-filter>
22         </activity>
23     </application>
24     
25 </manifest>

 

2.java
(1)MainActivity.java

 1 import java.util.ArrayList;
 2 import java.util.HashMap;
 3 import java.util.List;
 4 import java.util.Map;
 5 
 6 import org.marsdroid.model.WeiBoList;
 7 
 8 import oauth.signpost.OAuth;
 9 import android.app.Activity;
10 import android.content.Intent;
11 import android.content.SharedPreferences;
12 import android.os.Bundle;
13 import android.preference.PreferenceManager;
14 import android.view.View;
15 import android.view.View.OnClickListener;
16 import android.widget.Button;
17 
18 import com.google.gson.Gson;
19 
20 public class MainActivity extends Activity {
21     
22     final String TAG = getClass().getName();
23     private SharedPreferences prefs;
24     /** Called when the activity is first created. */
25     @Override
26     public void onCreate(Bundle savedInstanceState) {
27         super.onCreate(savedInstanceState);
28         setContentView(R.layout.main);
29         
30         prefs = PreferenceManager.getDefaultSharedPreferences(this);
31         Button launchOauth = (Button) findViewById(R.id.btn_launch_oauth);
32         Button sendWeiBoButton = (Button)findViewById(R.id.btn_sendWeiBo);
33         Button getWeiBoListButton = (Button)findViewById(R.id.btn_getWeiBoList);
34         
35         sendWeiBoButton.setOnClickListener(new OnClickListener() {
36             
37             @Override
38             public void onClick(View v) {
39                 //收集需要向腾讯微博服务器端发送的数据
40                 Map<String,String> map = new HashMap<String,String>();
41                 map.put("content", "test");
42                 map.put("clientip", "127.0.0.1");
43                 map.put("format", "json");
44                 //URL编码
45                 List<String> decodeNames = new ArrayList<String>();
46                 decodeNames.add("oauth_signature");
47                 //生成WeiboClient对象需要四个参数:Consumer_key,Consumer_key_secret,Oauth_tokent,OAuth_token_secret
48                 String OAuth_token = prefs.getString(OAuth.OAUTH_TOKEN, "");
49                 String OAuth_token_secret = prefs.getString(OAuth.OAUTH_TOKEN_SECRET, "");
50                 WeiBoClient weiBoClient = new WeiBoClient(Constants.CONSUMER_KEY, Constants.CONSUMER_SECRET, OAuth_token, OAuth_token_secret);
51                 weiBoClient.doPost("http://open.t.qq.com/api/t/add",map,decodeNames);
52             }
53         });
54         
55         getWeiBoListButton.setOnClickListener(new OnClickListener(){
56 
57             @Override
58             public void onClick(View v) {
59                 Map<String,String> keyValues = new HashMap<String,String>();
60                 keyValues.put("format", "json");
61                 keyValues.put("pageflag", "0");
62                 keyValues.put("pagetime", "0");
63                 keyValues.put("reqnum", "20");
64                 String OAuth_token = prefs.getString(OAuth.OAUTH_TOKEN, "");
65                 String OAuth_token_secret = prefs.getString(OAuth.OAUTH_TOKEN_SECRET, "");
66                 WeiBoClient weiBoClient = new WeiBoClient(Constants.CONSUMER_KEY, Constants.CONSUMER_SECRET, OAuth_token, OAuth_token_secret);
67                 String result = weiBoClient.doGet(Constants.WeiBoApi.HOME_TIMELINE, keyValues);
68                 System.out.println("result--->" + result);
69                 Gson gson = new Gson();
70                 WeiBoList weiBoList = gson.fromJson(result, WeiBoList.class);
71                 System.out.println("WeiBoList--->" + weiBoList);
72             }
73             
74         });
75         
76         launchOauth.setOnClickListener(new OnClickListener() {
77             public void onClick(View v) {
78                 startActivity(new Intent().setClass(v.getContext(), PrepareRequestTokenActivity.class));
79             }
80         });
81     }
82 
83 }

(2)WeiBoClient.java

  1 import java.util.List;
  2 import java.util.Map;
  3 
  4 import oauth.signpost.OAuthConsumer;
  5 import oauth.signpost.commonshttp.CommonsHttpOAuthConsumer;
  6 
  7 import org.apache.http.Header;
  8 import org.apache.http.HttpEntity;
  9 import org.apache.http.HttpResponse;
 10 import org.apache.http.NameValuePair;
 11 import org.apache.http.client.HttpClient;
 12 import org.apache.http.client.entity.UrlEncodedFormEntity;
 13 import org.apache.http.client.methods.HttpGet;
 14 import org.apache.http.client.methods.HttpPost;
 15 import org.apache.http.impl.client.DefaultHttpClient;
 16 import org.marsdroid.oauth04.utils.ApacheUtils;
 17 import org.marsdroid.oauth04.utils.HttpUtils;
 18 import org.marsdroid.oauth04.utils.OAuthUtils;
 19 import org.marsdroid.oauth04.utils.StringUtils;
 20 import org.marsdroid.oauth04.utils.UrlUtils;
 21 
 22 public class WeiBoClient {
 23     private OAuthConsumer consumer;
 24 
 25     public WeiBoClient() {
 26 
 27     }
 28 
 29     public WeiBoClient(String consumerKey, String consumerSecret,
 30             String oauthToken, String oauthTokenSecret) {
 31         // 生成一个OAuthConsumer对象
 32         consumer = new CommonsHttpOAuthConsumer(consumerKey, consumerSecret);
 33         // 设置OAuth_Token和OAuth_Token_Secret
 34         consumer.setTokenWithSecret(oauthToken, oauthTokenSecret);
 35     }
 36 
 37     public String doGet(String url, Map<String, String> addtionalParams) {
 38         String result = null;
 39         url = UrlUtils.buildUrlByQueryStringMapAndBaseUrl(url, addtionalParams);
 40         String signedUrl = null;
 41         try {
 42             System.out.println("签名之前的URL--->" + url);
 43             signedUrl = consumer.sign(url);
 44             System.out.println("签名之后的URL--->" + signedUrl);
 45         } catch (Exception e) {
 46             e.printStackTrace();
 47         }
 48         HttpGet getRequest = new HttpGet(signedUrl);
 49         HttpClient httpClient = new DefaultHttpClient();
 50         HttpResponse response = null;
 51         try {
 52             response = httpClient.execute(getRequest);
 53         } catch (Exception e) {
 54             // TODO Auto-generated catch block
 55             e.printStackTrace();
 56         }
 57         result = ApacheUtils.parseStringFromEntity(response.getEntity());
 58         return result;
 59     }
 60 
 61     public String doPost(String url, Map<String, String> addtionalParams,
 62             List<String> decodeNames) {
 63         // 生成一个HttpPost对象
 64         HttpPost postRequest = new HttpPost(url);
 65         consumer = OAuthUtils.addAddtionalParametersFromMap(consumer,
 66                 addtionalParams);
 67         try {
 68             consumer.sign(postRequest);
 69         } catch (Exception e) {
 70             e.printStackTrace();
 71         }
 72 
 73         Header oauthHeader = postRequest.getFirstHeader("Authorization");
 74         System.out.println(oauthHeader.getValue());
 75         String baseString = oauthHeader.getValue().substring(5).trim();
 76         Map<String, String> oauthMap = StringUtils
 77                 .parseMapFromString(baseString);
 78         oauthMap = HttpUtils.decodeByDecodeNames(decodeNames, oauthMap);
 79         addtionalParams = HttpUtils.decodeByDecodeNames(decodeNames,
 80                 addtionalParams);
 81         List<NameValuePair> pairs = ApacheUtils
 82                 .convertMapToNameValuePairs(oauthMap);
 83         List<NameValuePair> weiboPairs = ApacheUtils
 84                 .convertMapToNameValuePairs(addtionalParams);
 85         pairs.addAll(weiboPairs);
 86 
 87         HttpEntity entity = null;
 88         HttpResponse response = null;
 89         try {
 90             entity = new UrlEncodedFormEntity(pairs);
 91             postRequest.setEntity(entity);
 92             response = new DefaultHttpClient().execute(postRequest);
 93         } catch (Exception e) {
 94             e.printStackTrace();
 95         }
 96 
 97         String result = ApacheUtils.getResponseText(response);
 98 
 99         return result;
100     }
101 }

 

(3)PrepareRequestTokenActivity.java(和上个例子一样)

 

 1 import oauth.signpost.OAuthConsumer;
 2 import oauth.signpost.OAuthProvider;
 3 import oauth.signpost.commonshttp.CommonsHttpOAuthConsumer;
 4 import oauth.signpost.commonshttp.CommonsHttpOAuthProvider;
 5 import android.app.Activity;
 6 import android.content.Intent;
 7 import android.content.SharedPreferences;
 8 import android.net.Uri;
 9 import android.os.Bundle;
10 import android.preference.PreferenceManager;
11 
12 public class PrepareRequestTokenActivity extends Activity {
13 
14     private OAuthConsumer consumer;
15     private OAuthProvider provider;
16 
17     @Override
18     protected void onCreate(Bundle savedInstanceState) {
19         // TODO Auto-generated method stub
20         super.onCreate(savedInstanceState);
21 
22         System.setProperty("debug", "true");
23         consumer = new CommonsHttpOAuthConsumer(Constants.CONSUMER_KEY,
24                 Constants.CONSUMER_SECRET);
25         provider = new CommonsHttpOAuthProvider(Constants.REQUEST_URL,
26                 Constants.ACCESS_URL, Constants.AUTHORIZE_URL);
27 
28         new OAuthRequestTokenTask(this, consumer, provider).execute();
29     }
30 
31     @Override
32     public void onNewIntent(Intent intent) {
33         super.onNewIntent(intent);
34         SharedPreferences prefs = PreferenceManager
35                 .getDefaultSharedPreferences(this);
36         final Uri uri = intent.getData();
37         System.out.println(uri.toString());
38         if (uri != null
39                 && uri.getScheme().equals(Constants.OAUTH_CALLBACK_SCHEME)) {
40             new RetrieveAccessTokenTask(this, consumer, provider, prefs)
41                     .execute(uri);
42             finish();
43         }
44     }
45 }

 

 

(4)Constants.java

 1 public class Constants {
 2 
 3     public static final String CONSUMER_KEY     = "99e9494ff07e42489f4ace16b63e1f47";
 4     public static final String CONSUMER_SECRET     = "154f6f9ab4c1cf527f8ad8ab1f8e1ec9";
 5 
 6     public static final String REQUEST_URL         = "https://open.t.qq.com/cgi-bin/request_token";
 7     public static final String ACCESS_URL         = "https://open.t.qq.com/cgi-bin/access_token";  
 8     public static final String AUTHORIZE_URL     = "https://open.t.qq.com/cgi-bin/authorize";
 9     
10     public static final String ENCODING         = "UTF-8";
11     
12     public static final String    OAUTH_CALLBACK_SCHEME    = "x-oauthflow";
13     public static final String    OAUTH_CALLBACK_HOST        = "callback";
14     public static final String    OAUTH_CALLBACK_URL        = OAUTH_CALLBACK_SCHEME + "://" + OAUTH_CALLBACK_HOST;
15     class WeiBoApi{
16         //主页时间线
17         public static final String HOME_TIMELINE = "http://open.t.qq.com/api/statuses/home_timeline";
18         //我发表的时间线
19         public static final String BROADCAST_TIMELINE = "http://open.t.qq.com/api/statuses/broadcast_timeline";
20         //@到我的时间线
21         public static final String MENTIONS_TIMELINE = "http://open.t.qq.com/api/statuses/mentions_timeline";
22         //发表一条新微博
23         public static final String ADD = "http://open.t.qq.com/api/t/add";
24         //删除一条微博
25         public static final String DEL = "http://open.t.qq.com/api/t/del";
26         
27         
28     }
29 }

 

(5)WeiBoListData.java

 1 import java.util.ArrayList;
 2 import java.util.List;
 3 
 4 public class WeiBoListData {
 5     private long timestamp;
 6     private int hasnext;
 7     private int totalNum;
 8     private List<WeiBoData> info = new ArrayList<WeiBoData>();
 9     public List<WeiBoData> getInfo() {
10         return info;
11     }
12     public void setInfo(List<WeiBoData> info) {
13         this.info = info;
14     }
15     public WeiBoListData(long timestamp, int hasnext, int totalNum) {
16         super();
17         this.timestamp = timestamp;
18         this.hasnext = hasnext;
19         this.totalNum = totalNum;
20     }
21     public WeiBoListData() {
22         super();
23     }
24     public long getTimestamp() {
25         return timestamp;
26     }
27     public void setTimestamp(long timestamp) {
28         this.timestamp = timestamp;
29     }
30     public int getHasnext() {
31         return hasnext;
32     }
33     public void setHasnext(int hasnext) {
34         this.hasnext = hasnext;
35     }
36     public int getTotalNum() {
37         return totalNum;
38     }
39     public void setTotalNum(int totalNum) {
40         this.totalNum = totalNum;
41     }
42     @Override
43     public String toString() {
44         return "WeiBoListData [hasnext=" + hasnext + ", info=" + info
45                 + ", timestamp=" + timestamp + ", totalNum=" + totalNum + "]";
46     }
47     
48 }

 

(6)WeiBoList.java

 1 public class WeiBoList {
 2     private int ret;
 3     private String msg;
 4     private int errcode;
 5     private WeiBoListData data;
 6 
 7     public WeiBoList(int ret, String msg, int errcode, WeiBoListData data) {
 8         super();
 9         this.ret = ret;
10         this.msg = msg;
11         this.errcode = errcode;
12         this.data = data;
13     }
14 
15     public WeiBoList() {
16         super();
17     }
18 
19     public int getRet() {
20         return ret;
21     }
22 
23     public void setRet(int ret) {
24         this.ret = ret;
25     }
26 
27     public String getMsg() {
28         return msg;
29     }
30 
31     public void setMsg(String msg) {
32         this.msg = msg;
33     }
34 
35     public int getErrcode() {
36         return errcode;
37     }
38 
39     public void setErrcode(int errcode) {
40         this.errcode = errcode;
41     }
42 
43     public WeiBoListData getData() {
44         return data;
45     }
46 
47     public void setData(WeiBoListData data) {
48         this.data = data;
49     }
50 
51     @Override
52     public String toString() {
53         return "WeiBoList [data=" + data + ", errcode=" + errcode + ", msg="
54                 + msg + ", ret=" + ret + "]";
55     }
56     
57 }

 

(7)WeiBoData.java

  1 import java.util.List;
  2 
  3 //单条微博数据模型对象
  4 
  5 public class WeiBoData {
  6     private String text;
  7     private String origtext;
  8     private int count;
  9     private int mcount;
 10     private String from;
 11     private long id;
 12     //private image
 13     private String name;
 14     private String nick;
 15     private String uid;
 16     private int self;
 17     private long timestamp;
 18     private int type;
 19     private String head;
 20     private String location;
 21     private String country_code;
 22     private String province_code;
 23     private String city_code;
 24     private int isVip;
 25     private int status;
 26     private WeiBoData source;
 27     private List<String> image;
 28     public List<String> getImage() {
 29         return image;
 30     }
 31     public void setImage(List<String> image) {
 32         this.image = image;
 33     }
 34     public WeiBoData getSource() {
 35         return source;
 36     }
 37     public void setSource(WeiBoData source) {
 38         this.source = source;
 39     }
 40     
 41 
 42     @Override
 43     public String toString() {
 44         return "WeiBoData [city_code=" + city_code + ", count=" + count
 45                 + ", country_code=" + country_code + ", from=" + from
 46                 + ", head=" + head + ", id=" + id + ", image=" + image
 47                 + ", isVip=" + isVip + ", location=" + location + ", mcount="
 48                 + mcount + ", name=" + name + ", nick=" + nick + ", origtext="
 49                 + origtext + ", province_code=" + province_code + ", self="
 50                 + self + ", source=" + source + ", status=" + status
 51                 + ", text=" + text + ", timestamp=" + timestamp + ", type="
 52                 + type + ", uid=" + uid + "]";
 53     }
 54     public String getText() {
 55         return text;
 56     }
 57     public void setText(String text) {
 58         this.text = text;
 59     }
 60     public String getOrigtext() {
 61         return origtext;
 62     }
 63     public void setOrigtext(String origtext) {
 64         this.origtext = origtext;
 65     }
 66     public int getCount() {
 67         return count;
 68     }
 69     public void setCount(int count) {
 70         this.count = count;
 71     }
 72     public int getMcount() {
 73         return mcount;
 74     }
 75     public void setMcount(int mcount) {
 76         this.mcount = mcount;
 77     }
 78     public String getFrom() {
 79         return from;
 80     }
 81     public void setFrom(String from) {
 82 

以上是关于ANDROID_MARS学习笔记_S04_007_从服务器获取微博数据时间线的主要内容,如果未能解决你的问题,请参考以下文章

ANDROID_MARS学习笔记_S02_007_Animation第一种使用方式:代码

ANDROID_MARS学习笔记_S01原始版_007_Handler及线程的简单使用

ANDROID_MARS学习笔记_S01_007Linear_layout嵌套与layout_weight的设置

ANDROID_MARS学习笔记_S04_001_OAuth简介

ANDROID_MARS学习笔记_S04_002_用AsyncTask实现异步操作

ANDROID_MARS学习笔记_S04_004_用HTTPCLENT发带参数的get和post请求