一、代码

1.xml
(1)activity_main.xml

 <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<Button android:id="@+id/btn_launch_oauth"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Launch OAuth Flow"/> <Button
android:id="@+id/btn_sendWeiBo"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="发送一条微博消息"
/>
<Button
android:id="@+id/btn_getWeiBoList"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="得到主页时间线数据"
/>
</LinearLayout>

(2)AndroidManifest.xml

 <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="org.marsdroid.oauth04"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="10" />
<uses-permission android:name="android.permission.INTERNET" />
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".MainActivity" android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".PrepareRequestTokenActivity" android:launchMode="singleTask">
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="x-oauthflow" android:host="callback" />
</intent-filter>
</activity>
</application> </manifest>

2.java
(1)MainActivity.java

 import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map; import org.marsdroid.model.WeiBoList; import oauth.signpost.OAuth;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button; import com.google.gson.Gson; public class MainActivity extends Activity { final String TAG = getClass().getName();
private SharedPreferences prefs;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main); prefs = PreferenceManager.getDefaultSharedPreferences(this);
Button launchOauth = (Button) findViewById(R.id.btn_launch_oauth);
Button sendWeiBoButton = (Button)findViewById(R.id.btn_sendWeiBo);
Button getWeiBoListButton = (Button)findViewById(R.id.btn_getWeiBoList); sendWeiBoButton.setOnClickListener(new OnClickListener() { @Override
public void onClick(View v) {
//收集需要向腾讯微博服务器端发送的数据
Map<String,String> map = new HashMap<String,String>();
map.put("content", "test");
map.put("clientip", "127.0.0.1");
map.put("format", "json");
//URL编码
List<String> decodeNames = new ArrayList<String>();
decodeNames.add("oauth_signature");
//生成WeiboClient对象需要四个参数:Consumer_key,Consumer_key_secret,Oauth_tokent,OAuth_token_secret
String OAuth_token = prefs.getString(OAuth.OAUTH_TOKEN, "");
String OAuth_token_secret = prefs.getString(OAuth.OAUTH_TOKEN_SECRET, "");
WeiBoClient weiBoClient = new WeiBoClient(Constants.CONSUMER_KEY, Constants.CONSUMER_SECRET, OAuth_token, OAuth_token_secret);
weiBoClient.doPost("http://open.t.qq.com/api/t/add",map,decodeNames);
}
}); getWeiBoListButton.setOnClickListener(new OnClickListener(){ @Override
public void onClick(View v) {
Map<String,String> keyValues = new HashMap<String,String>();
keyValues.put("format", "json");
keyValues.put("pageflag", "0");
keyValues.put("pagetime", "0");
keyValues.put("reqnum", "20");
String OAuth_token = prefs.getString(OAuth.OAUTH_TOKEN, "");
String OAuth_token_secret = prefs.getString(OAuth.OAUTH_TOKEN_SECRET, "");
WeiBoClient weiBoClient = new WeiBoClient(Constants.CONSUMER_KEY, Constants.CONSUMER_SECRET, OAuth_token, OAuth_token_secret);
String result = weiBoClient.doGet(Constants.WeiBoApi.HOME_TIMELINE, keyValues);
System.out.println("result--->" + result);
Gson gson = new Gson();
WeiBoList weiBoList = gson.fromJson(result, WeiBoList.class);
System.out.println("WeiBoList--->" + weiBoList);
} }); launchOauth.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
startActivity(new Intent().setClass(v.getContext(), PrepareRequestTokenActivity.class));
}
});
} }

(2)WeiBoClient.java

 import java.util.List;
import java.util.Map; import oauth.signpost.OAuthConsumer;
import oauth.signpost.commonshttp.CommonsHttpOAuthConsumer; import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.marsdroid.oauth04.utils.ApacheUtils;
import org.marsdroid.oauth04.utils.HttpUtils;
import org.marsdroid.oauth04.utils.OAuthUtils;
import org.marsdroid.oauth04.utils.StringUtils;
import org.marsdroid.oauth04.utils.UrlUtils; public class WeiBoClient {
private OAuthConsumer consumer; public WeiBoClient() { } public WeiBoClient(String consumerKey, String consumerSecret,
String oauthToken, String oauthTokenSecret) {
// 生成一个OAuthConsumer对象
consumer = new CommonsHttpOAuthConsumer(consumerKey, consumerSecret);
// 设置OAuth_Token和OAuth_Token_Secret
consumer.setTokenWithSecret(oauthToken, oauthTokenSecret);
} public String doGet(String url, Map<String, String> addtionalParams) {
String result = null;
url = UrlUtils.buildUrlByQueryStringMapAndBaseUrl(url, addtionalParams);
String signedUrl = null;
try {
System.out.println("签名之前的URL--->" + url);
signedUrl = consumer.sign(url);
System.out.println("签名之后的URL--->" + signedUrl);
} catch (Exception e) {
e.printStackTrace();
}
HttpGet getRequest = new HttpGet(signedUrl);
HttpClient httpClient = new DefaultHttpClient();
HttpResponse response = null;
try {
response = httpClient.execute(getRequest);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
result = ApacheUtils.parseStringFromEntity(response.getEntity());
return result;
} public String doPost(String url, Map<String, String> addtionalParams,
List<String> decodeNames) {
// 生成一个HttpPost对象
HttpPost postRequest = new HttpPost(url);
consumer = OAuthUtils.addAddtionalParametersFromMap(consumer,
addtionalParams);
try {
consumer.sign(postRequest);
} catch (Exception e) {
e.printStackTrace();
} Header oauthHeader = postRequest.getFirstHeader("Authorization");
System.out.println(oauthHeader.getValue());
String baseString = oauthHeader.getValue().substring(5).trim();
Map<String, String> oauthMap = StringUtils
.parseMapFromString(baseString);
oauthMap = HttpUtils.decodeByDecodeNames(decodeNames, oauthMap);
addtionalParams = HttpUtils.decodeByDecodeNames(decodeNames,
addtionalParams);
List<NameValuePair> pairs = ApacheUtils
.convertMapToNameValuePairs(oauthMap);
List<NameValuePair> weiboPairs = ApacheUtils
.convertMapToNameValuePairs(addtionalParams);
pairs.addAll(weiboPairs); HttpEntity entity = null;
HttpResponse response = null;
try {
entity = new UrlEncodedFormEntity(pairs);
postRequest.setEntity(entity);
response = new DefaultHttpClient().execute(postRequest);
} catch (Exception e) {
e.printStackTrace();
} String result = ApacheUtils.getResponseText(response); return result;
}
}

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

 import oauth.signpost.OAuthConsumer;
import oauth.signpost.OAuthProvider;
import oauth.signpost.commonshttp.CommonsHttpOAuthConsumer;
import oauth.signpost.commonshttp.CommonsHttpOAuthProvider;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager; public class PrepareRequestTokenActivity extends Activity { private OAuthConsumer consumer;
private OAuthProvider provider; @Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState); System.setProperty("debug", "true");
consumer = new CommonsHttpOAuthConsumer(Constants.CONSUMER_KEY,
Constants.CONSUMER_SECRET);
provider = new CommonsHttpOAuthProvider(Constants.REQUEST_URL,
Constants.ACCESS_URL, Constants.AUTHORIZE_URL); new OAuthRequestTokenTask(this, consumer, provider).execute();
} @Override
public void onNewIntent(Intent intent) {
super.onNewIntent(intent);
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(this);
final Uri uri = intent.getData();
System.out.println(uri.toString());
if (uri != null
&& uri.getScheme().equals(Constants.OAUTH_CALLBACK_SCHEME)) {
new RetrieveAccessTokenTask(this, consumer, provider, prefs)
.execute(uri);
finish();
}
}
}

(4)Constants.java

 public class Constants {

     public static final String CONSUMER_KEY     = "99e9494ff07e42489f4ace16b63e1f47";
public static final String CONSUMER_SECRET = "154f6f9ab4c1cf527f8ad8ab1f8e1ec9"; public static final String REQUEST_URL = "https://open.t.qq.com/cgi-bin/request_token";
public static final String ACCESS_URL = "https://open.t.qq.com/cgi-bin/access_token";
public static final String AUTHORIZE_URL = "https://open.t.qq.com/cgi-bin/authorize"; public static final String ENCODING = "UTF-8"; public static final String OAUTH_CALLBACK_SCHEME = "x-oauthflow";
public static final String OAUTH_CALLBACK_HOST = "callback";
public static final String OAUTH_CALLBACK_URL = OAUTH_CALLBACK_SCHEME + "://" + OAUTH_CALLBACK_HOST;
class WeiBoApi{
//主页时间线
public static final String HOME_TIMELINE = "http://open.t.qq.com/api/statuses/home_timeline";
//我发表的时间线
public static final String BROADCAST_TIMELINE = "http://open.t.qq.com/api/statuses/broadcast_timeline";
//@到我的时间线
public static final String MENTIONS_TIMELINE = "http://open.t.qq.com/api/statuses/mentions_timeline";
//发表一条新微博
public static final String ADD = "http://open.t.qq.com/api/t/add";
//删除一条微博
public static final String DEL = "http://open.t.qq.com/api/t/del"; }
}

(5)WeiBoListData.java

 import java.util.ArrayList;
import java.util.List; public class WeiBoListData {
private long timestamp;
private int hasnext;
private int totalNum;
private List<WeiBoData> info = new ArrayList<WeiBoData>();
public List<WeiBoData> getInfo() {
return info;
}
public void setInfo(List<WeiBoData> info) {
this.info = info;
}
public WeiBoListData(long timestamp, int hasnext, int totalNum) {
super();
this.timestamp = timestamp;
this.hasnext = hasnext;
this.totalNum = totalNum;
}
public WeiBoListData() {
super();
}
public long getTimestamp() {
return timestamp;
}
public void setTimestamp(long timestamp) {
this.timestamp = timestamp;
}
public int getHasnext() {
return hasnext;
}
public void setHasnext(int hasnext) {
this.hasnext = hasnext;
}
public int getTotalNum() {
return totalNum;
}
public void setTotalNum(int totalNum) {
this.totalNum = totalNum;
}
@Override
public String toString() {
return "WeiBoListData [hasnext=" + hasnext + ", info=" + info
+ ", timestamp=" + timestamp + ", totalNum=" + totalNum + "]";
} }

(6)WeiBoList.java

 public class WeiBoList {
private int ret;
private String msg;
private int errcode;
private WeiBoListData data; public WeiBoList(int ret, String msg, int errcode, WeiBoListData data) {
super();
this.ret = ret;
this.msg = msg;
this.errcode = errcode;
this.data = data;
} public WeiBoList() {
super();
} public int getRet() {
return ret;
} public void setRet(int ret) {
this.ret = ret;
} public String getMsg() {
return msg;
} public void setMsg(String msg) {
this.msg = msg;
} public int getErrcode() {
return errcode;
} public void setErrcode(int errcode) {
this.errcode = errcode;
} public WeiBoListData getData() {
return data;
} public void setData(WeiBoListData data) {
this.data = data;
} @Override
public String toString() {
return "WeiBoList [data=" + data + ", errcode=" + errcode + ", msg="
+ msg + ", ret=" + ret + "]";
} }

(7)WeiBoData.java

 import java.util.List;

 //单条微博数据模型对象

 public class WeiBoData {
private String text;
private String origtext;
private int count;
private int mcount;
private String from;
private long id;
//private image
private String name;
private String nick;
private String uid;
private int self;
private long timestamp;
private int type;
private String head;
private String location;
private String country_code;
private String province_code;
private String city_code;
private int isVip;
private int status;
private WeiBoData source;
private List<String> image;
public List<String> getImage() {
return image;
}
public void setImage(List<String> image) {
this.image = image;
}
public WeiBoData getSource() {
return source;
}
public void setSource(WeiBoData source) {
this.source = source;
} @Override
public String toString() {
return "WeiBoData [city_code=" + city_code + ", count=" + count
+ ", country_code=" + country_code + ", from=" + from
+ ", head=" + head + ", id=" + id + ", image=" + image
+ ", isVip=" + isVip + ", location=" + location + ", mcount="
+ mcount + ", name=" + name + ", nick=" + nick + ", origtext="
+ origtext + ", province_code=" + province_code + ", self="
+ self + ", source=" + source + ", status=" + status
+ ", text=" + text + ", timestamp=" + timestamp + ", type="
+ type + ", uid=" + uid + "]";
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public String getOrigtext() {
return origtext;
}
public void setOrigtext(String origtext) {
this.origtext = origtext;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
public int getMcount() {
return mcount;
}
public void setMcount(int mcount) {
this.mcount = mcount;
}
public String getFrom() {
return from;
}
public void setFrom(String from) {
this.from = from;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getNick() {
return nick;
}
public void setNick(String nick) {
this.nick = nick;
}
public String getUid() {
return uid;
}
public void setUid(String uid) {
this.uid = uid;
}
public int getSelf() {
return self;
}
public void setSelf(int self) {
this.self = self;
}
public long getTimestamp() {
return timestamp;
}
public void setTimestamp(long timestamp) {
this.timestamp = timestamp;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
public String getHead() {
return head;
}
public void setHead(String head) {
this.head = head;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
} public String getCountry_code() {
return country_code;
}
public void setCountry_code(String countryCode) {
country_code = countryCode;
}
public String getProvince_code() {
return province_code;
}
public void setProvince_code(String provinceCode) {
province_code = provinceCode;
}
public String getCity_code() {
return city_code;
}
public void setCity_code(String cityCode) {
city_code = cityCode;
}
public int getIsVip() {
return isVip;
}
public void setIsVip(int isVip) {
this.isVip = isVip;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
}

ANDROID_MARS学习笔记_S04_007_从服务器获取微博数据时间线的更多相关文章

  1. ANDROID_MARS学习笔记_S05_001_用SensorManager获取传感器

    1. public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentV ...

  2. sqlserver -- 学习笔记(七)获取同组数据的前两条记录

    不啰嗦,直接上图,大概实现效果如下: 有上面这样一份数据,将他们按照userAccount和submitTime进行分组,然后提前每组数据的前两条记录 提取后数据如下: 实现的SQL如下: selec ...

  3. ANDROID_MARS学习笔记_S02_012_ANIMATION_利用AnimationListener在动画结束时删除或添加组件

    一.代码 1.xml(1)activity_main.xml <?xml version="1.0" encoding="utf-8"?> < ...

  4. ASP.NET MVC 学习笔记-7.自定义配置信息 ASP.NET MVC 学习笔记-6.异步控制器 ASP.NET MVC 学习笔记-5.Controller与View的数据传递 ASP.NET MVC 学习笔记-4.ASP.NET MVC中Ajax的应用 ASP.NET MVC 学习笔记-3.面向对象设计原则

    ASP.NET MVC 学习笔记-7.自定义配置信息   ASP.NET程序中的web.config文件中,在appSettings这个配置节中能够保存一些配置,比如, 1 <appSettin ...

  5. Caffe学习笔记(三):Caffe数据是如何输入和输出的?

    Caffe学习笔记(三):Caffe数据是如何输入和输出的? Caffe中的数据流以Blobs进行传输,在<Caffe学习笔记(一):Caffe架构及其模型解析>中已经对Blobs进行了简 ...

  6. android 从服务器获取新闻数据并显示在客户端

    新闻客户端案例 第一次进入新闻客户端需要请求服务器获取新闻数据,做listview的展示, 为了第二次再次打开新闻客户端时能快速显示新闻,需要将数据缓存到数据库中,下次打开可以直接去数据库中获取新闻直 ...

  7. [iOS微博项目 - 2.6] - 获取微博数据

    github: https://github.com/hellovoidworld/HVWWeibo   A.新浪获取微博API 1.读取微博API     2.“statuses/home_time ...

  8. VSTO学习笔记(十四)Excel数据透视表与PowerPivot

    原文:VSTO学习笔记(十四)Excel数据透视表与PowerPivot 近期公司内部在做一种通用查询报表,方便人力资源分析.统计数据.由于之前公司系统中有一个类似的查询使用Excel数据透视表完成的 ...

  9. Spring MVC 学习笔记11 —— 后端返回json格式数据

    Spring MVC 学习笔记11 -- 后端返回json格式数据 我们常常听说json数据,首先,什么是json数据,总结起来,有以下几点: 1. JSON的全称是"JavaScript ...

随机推荐

  1. 11.14 noip模拟试题

      题目名称 正确答案 序列问题 长途旅行 英文名称 answer sequence travel 输入文件名 answer.in sequence.in travel.in 输出文件名 answer ...

  2. JLabel跟label

  3. order by跟group by 跟having(2)

  4. selenium2.0处理case实例(一)

    通过自动化脚本, 判断下拉框选项值是否按照字母顺序(忽略大小写)显示 case场景如下: 1)打开www.test.com;2)判断下拉框选项是否按照字母顺序排列(忽略大小写)3)选择其中一个任意选项 ...

  5. 文件打开方式O_DSYNC、O_RSYNC、O_SYNC

    O_DSYNC: 每次write都等待物理I/O完成,但是如果写操作不影响读取刚写入的数据,则不等待文件属性更新 O_RSYNC: 每个以文件描述符作为参数的read操作等待,直到所有对文件同一部分的 ...

  6. Web Service 的服务端的引用

    1.先说说服务端的引用 先写一个Web Service 的文件  上图 创建一个web 项目或者网站  然后添加新项 创建一个web服务 得到 下面的页面 然后运行起来 然后复制下地址 接下来创建另一 ...

  7. mod_wsgi

    配置: WSGIScriptAlias /var/www/wsgi-scripts/simple.wsgi def application(environ, start_response): outp ...

  8. Ubuntu下gcc及g++环境配置

    直接在命令行中输入以下命令即可. sudo apt-get install build-essential 安装完成后输入 gcc 和 g++ 进行确认.

  9. 包管理器Bower使用手册之一

    包管理器Bower使用手册之一 作者:chszs,转载需注明.博客主页:http://blog.csdn.net/chszs 一.Bower介绍 Bower是一个适合Web应用的包管理器,它擅长前端的 ...

  10. 在同一台机器上让Microsoft SQL Server 2000/ SQL2005/ SQL2008共存

    可能很多朋友都遇到想同时在自己的机器上运行Microsoft SQL Server 2000以及Microsoft SQL Server 2005和Microsoft SQL Server 2008. ...