一、代码
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;
}
}