一、代码

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. sqlserver2008中如何用右键可视化的设置外键

    右键->设计 然后打表设计界面打开了然后右键点你要设置与其它表关联的列然后点关系,选择外键表与列然后点保存,就这样  

  2. Hibernate缓存杂谈

    1.什么是缓存? 缓存是介于物理数据源与应用程序之间,是对数据库中的数据复制一份临时放在内存中的容器,其作用是为了减少应用程序对物理数据源访问的次数,从而提高了应用程序的运行性能.Hibernate在 ...

  3. ASP与ASP.NET转换Session数据桥的应用

    背景: 现有公司的产品OA是采用ASP早先的技术开发,需要与目前最新的ASP.NET产品进行数据交互的应用.现有的ASP应用程序往往采用“ASP Sessions”,这是一种经典的ASP内置模式,即允 ...

  4. socket的NIO操作

    一.前言 Java中直接使用socket进行通信的场景应该不是很多,在公司的一个项目中有这种需求,所以根据自己的理解和相关资料的参考,基于NIO 实现了一组工具类库,具体的协议还未定义,后续再整理 二 ...

  5. 总结一下const和readonly

    const和readonly的值一旦初始化则都不再可以改写: const只能在声明时初始化:readonly既可以在声明时初始化也可以在构造器中初始化: const隐含static,不可以再写stat ...

  6. c++ 学习之const专题之const成员函数

    一些成员函数改变对象,一些成员函数不改变对象. 例如: int Point::GetY() { return yVal; } 这个函数被调用时,不改变Point对象,而下面的函数改变Point对象: ...

  7. oracle定时备份

    1.将如下代码复制到文本中,最后将文本后缀名称修改成XXX.bat 批处理文件: *********************************************************** ...

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

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

  9. Objective-C description的用法

    description类似于.net/java ToString()方法的用途. 假设有一个CTPerson类, - (NSString *)description { return @"d ...

  10. O-C相关-07-@property关键字简介与使用

    基本概念:在O-C中,创建完类之后还需要给一个类添加属性和方法,之前说过的set和get方法比较繁琐,因此引入了@property 这个编译器指令.@property 是一个编译器指令.所谓的编译器指 ...