码迷,mamicode.com
首页 > 移动开发 > 详细

ANDROID_MARS学习笔记_S04_005_用sing-post向腾讯微博发一条信息

时间:2016-02-22 12:09:39      阅读:225      评论:0      收藏:0      [点我收藏+]

标签:

一、代码流程

1.组织好sign-post需要的token,secrect

2.组织好发微博需要的信息

3.用sign-post进行签名

4.把签名结果从header中拿出来,转成entity,用httpclient以post的形式发送微博

二、简介

技术分享

技术分享

技术分享

三、代码
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="wrap_content"
 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="wrap_content"
15                 android:layout_height="wrap_content"
16                 android:text="发送一条微博消息"
17         />
18 </LinearLayout>

 

(2)AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="org.marsdroid.oauth03"
      android:versionCode="1"
      android:versionName="1.0">
    <uses-sdk android:minSdkVersion="10" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.READ_CONTACTS" />
    <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

 1 package org.marsdroid.oauth03;
 2 
 3 import java.util.ArrayList;
 4 import java.util.HashMap;
 5 import java.util.List;
 6 import java.util.Map;
 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 public class MainActivity extends Activity {
19     
20     final String TAG = getClass().getName();
21     private SharedPreferences prefs;
22     /** Called when the activity is first created. */
23     @Override
24     public void onCreate(Bundle savedInstanceState) {
25         super.onCreate(savedInstanceState);
26         setContentView(R.layout.main);
27         
28         prefs = PreferenceManager.getDefaultSharedPreferences(this);
29         Button launchOauth = (Button) findViewById(R.id.btn_launch_oauth);
30         Button sendWeiBoButton = (Button)findViewById(R.id.btn_sendWeiBo);
31  
32         sendWeiBoButton.setOnClickListener(new OnClickListener() {
33             
34             @Override
35             public void onClick(View v) {
36                 //收集需要向腾讯微博服务器端发送的数据
37                 Map<String,String> map = new HashMap<String,String>();
38                 map.put("content", "test");
39                 map.put("clientip", "127.0.0.1");
40                 map.put("format", "json");
41                 //URL编码
42                 List<String> decodeNames = new ArrayList<String>();
43                 decodeNames.add("oauth_signature");//最后生成的oauth_signature可以包含“=“等,所以要进行url编码
44                 //生成WeiboClient对象需要四个参数:Consumer_key,Consumer_key_secret,Oauth_tokent,OAuth_token_secret
45                 String OAuth_token = prefs.getString(OAuth.OAUTH_TOKEN, "");
46                 String OAuth_token_secret = prefs.getString(OAuth.OAUTH_TOKEN_SECRET, "");
47                 WeiBoClient weiBoClient = new WeiBoClient(Constants.CONSUMER_KEY, Constants.CONSUMER_SECRET, OAuth_token, OAuth_token_secret);
48                 weiBoClient.doPost("http://open.t.qq.com/api/t/add",map,decodeNames);
49             }
50         });
51         
52         
53         launchOauth.setOnClickListener(new OnClickListener() {
54             public void onClick(View v) {
55                 startActivity(new Intent().setClass(v.getContext(), PrepareRequestTokenActivity.class));
56             }
57         });
58     }

 

(2)Constants.java

 

 1 package org.marsdroid.oauth03;
 2 
 3 
 4 public class Constants {
 5 
 6     public static final String CONSUMER_KEY = "99e9494ff07e42489f4ace16b63e1f47";
 7     public static final String CONSUMER_SECRET     = "154f6f9ab4c1cf527f8ad8ab1f8e1ec9";
 8 
 9     public static final String REQUEST_URL         = "https://open.t.qq.com/cgi-bin/request_token";
10     public static final String ACCESS_URL         = "https://open.t.qq.com/cgi-bin/access_token";  
11     public static final String AUTHORIZE_URL     = "https://open.t.qq.com/cgi-bin/authorize";
12     
13     public static final String ENCODING         = "UTF-8";
14     
15     public static final String    OAUTH_CALLBACK_SCHEME    = "x-oauthflow";
16     public static final String    OAUTH_CALLBACK_HOST        = "callback";
17     public static final String    OAUTH_CALLBACK_URL        = OAUTH_CALLBACK_SCHEME + "://" + OAUTH_CALLBACK_HOST;
18 
19 }

 

 

(3)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.entity.UrlEncodedFormEntity;
12 import org.apache.http.client.methods.HttpPost;
13 import org.apache.http.impl.client.DefaultHttpClient;
14 import org.marsdroid.oauth03.utils.ApacheUtils;
15 import org.marsdroid.oauth03.utils.HttpUtils;
16 import org.marsdroid.oauth03.utils.OAuthUtils;
17 import org.marsdroid.oauth03.utils.StringUtils;
18 
19 public class WeiBoClient {
20     private OAuthConsumer consumer;
21     public WeiBoClient(){
22         
23     }
24     
25     public WeiBoClient(String consumerKey,String consumerSecret,String oauthToken,String oauthTokenSecret){
26         //生成一个OAuthConsumer对象
27         consumer = new CommonsHttpOAuthConsumer(consumerKey, consumerSecret);
28         //设置OAuth_Token和OAuth_Token_Secret
29         consumer.setTokenWithSecret(oauthToken, oauthTokenSecret);
30     }
31     public String doPost(String url,Map<String,String> addtionalParams,List<String> decodeNames){
32         //生成一个HttpPost对象
33         HttpPost postRequest = new HttpPost(url);
34         //把腾讯微博所需要的数据也加上
35         consumer = OAuthUtils.addAddtionalParametersFromMap(consumer, addtionalParams);
36         try {
37             //用sing-post对信息签名,sing-post会把签名结果放到header中,但腾讯不支持
38             consumer.sign(postRequest);
39         } catch (Exception e) {
40             e.printStackTrace();
41         }
42         
43         
44         Header oauthHeader = postRequest.getFirstHeader("Authorization");
45         System.out.println(oauthHeader.getValue());
46         String baseString = oauthHeader.getValue().substring(5).trim();
47         Map<String,String> oauthMap = StringUtils.parseMapFromString(baseString);
48         oauthMap = HttpUtils.decodeByDecodeNames(decodeNames, oauthMap);
49         addtionalParams = HttpUtils.decodeByDecodeNames(decodeNames, addtionalParams);
50         List<NameValuePair> pairs = ApacheUtils.convertMapToNameValuePairs(oauthMap);
51         List<NameValuePair> weiboPairs = ApacheUtils.convertMapToNameValuePairs(addtionalParams);
52         pairs.addAll(weiboPairs);
53         
54         HttpEntity entity = null;
55         HttpResponse response = null;
56         try {
57             entity = new UrlEncodedFormEntity(pairs);
58             postRequest.setEntity(entity);
59             response = new DefaultHttpClient().execute(postRequest);
60         } catch (Exception e) {
61             e.printStackTrace();
62         }
63         
64         String result = ApacheUtils.getResponseText(response); 
65         
66         return result;
67     }
68 }

 

(4)ApacheUtils.java

 1 package org.marsdroid.oauth03.utils;
 2 
 3 import java.io.BufferedReader;
 4 import java.io.InputStream;
 5 import java.io.InputStreamReader;
 6 import java.util.ArrayList;
 7 import java.util.Iterator;
 8 import java.util.List;
 9 import java.util.Map;
10 import java.util.Set;
11 
12 import org.apache.http.HttpEntity;
13 import org.apache.http.HttpResponse;
14 import org.apache.http.NameValuePair;
15 import org.apache.http.message.BasicNameValuePair;
16 
17 public class ApacheUtils {
18     public static List<NameValuePair> convertMapToNameValuePairs(Map<String, String> oauthMap) {
19         List<NameValuePair> pairs = new ArrayList<NameValuePair>();
20         Set<String> keys = oauthMap.keySet();
21         Iterator<String> it = keys.iterator();
22         while(it.hasNext()){
23             String key = it.next();
24             String value = oauthMap.get(key);
25             NameValuePair pair = new BasicNameValuePair(key, value);
26             pairs.add(pair);
27         }
28         return pairs;
29     }
30     public static String getResponseText(HttpResponse response) {
31         HttpEntity responseEntity = response.getEntity();
32         InputStream input = null;
33         String result = null;
34         try {
35             input = responseEntity.getContent();
36             BufferedReader reader = new BufferedReader(new InputStreamReader(input));
37             String line = null;
38             StringBuffer sb = new StringBuffer();
39             while((line = reader.readLine()) != null){
40                 sb.append(line);
41             }
42             result = sb.toString();
43             System.out.println("reuslt---->" + result);
44         } catch (Exception e) {
45             // TODO Auto-generated catch block
46             e.printStackTrace();
47         }
48         return result;
49     }
50     public static String parseStringFromEntity(HttpEntity entity){
51         String result = null;
52         try{
53             InputStream input = entity.getContent();
54             BufferedReader reader = new BufferedReader(new InputStreamReader(input));
55             String line = null;
56             StringBuffer sb = new StringBuffer();
57             while((line = reader.readLine()) != null){
58                 sb.append(line);
59             }
60             result = sb.toString();
61         }
62         catch(Exception e){
63             System.out.println(e);
64         }
65         return result;
66     }
67 }

 

(5)HttpUtils.java

 1 import java.net.URLDecoder;
 2 import java.util.Iterator;
 3 import java.util.List;
 4 import java.util.Map;
 5 import java.util.Set;
 6 
 7 public class HttpUtils {
 8     public static Map<String,String> decodeByDecodeNames(List<String> decodeNames,Map<String,String> map){
 9         Set<String> keys = map.keySet();
10         Iterator<String> it = keys.iterator();
11         while (it.hasNext()) {
12             String key = it.next();
13             String value = map.get(key);
14             for(String decodeName : decodeNames){
15                 if(key.equals(decodeName)){
16                     value = URLDecoder.decode(value);
17                     map.put(key, value);
18                 }
19             }
20         }
21         return map;
22     }
23 }

 

(6)OAuthUtils.java

 1 import java.util.Iterator;
 2 import java.util.Map;
 3 import java.util.Set;
 4 
 5 import oauth.signpost.OAuthConsumer;
 6 import oauth.signpost.http.HttpParameters;
 7 
 8 public class OAuthUtils {
 9     
10     public static OAuthConsumer addAddtionalParametersFromMap(OAuthConsumer consumer,
11             Map<String, String> addtionalParams) {
12         Set<String> keys = addtionalParams.keySet();
13         Iterator<String> it = keys.iterator();
14         
15         HttpParameters httpParameters = new HttpParameters();
16         while(it.hasNext()){
17             String key = it.next();
18             String value = addtionalParams.get(key);
19             httpParameters.put(key, value);
20         }
21         consumer.setAdditionalParameters(httpParameters);
22         return consumer;
23     }
24 }

 

(7)StringUtils.java

 1 import java.util.HashMap;
 2 import java.util.Map;
 3 
 4 public class StringUtils {
 5     //key1="value1",key2="value2"........
 6     public static Map<String,String> parseMapFromString(String baseString) {
 7         String [] arr = baseString.split(",");
 8         Map<String,String > result = new HashMap<String,String>();
 9         for (int i = 0; i < arr.length; i++) {
10             String temp [] = arr[i].split("=");
11             String key = temp[0].trim();
12             //去掉双引号
13             String value = temp[1].substring(1, temp[1].length()-1);
14             result.put(key, value);
15         }
16         return result;
17     }
18 }

 

(8)UrlUtils.java

 1 import java.util.ArrayList;
 2 import java.util.List;
 3 import java.util.Map;
 4 import java.util.Set;
 5 
 6 import org.apache.http.NameValuePair;
 7 import org.apache.http.client.utils.URLEncodedUtils;
 8 import org.apache.http.message.BasicNameValuePair;
 9 
10 public class UrlUtils {
11     public static String buildQueryString(Map<String,String> map){
12         List<NameValuePair> pairs = buildNameValuePairs(map);
13         String queryStr = URLEncodedUtils.format(pairs, "UTF-8");
14         return queryStr;
15     }
16     
17     public static String buildUrlByQueryStringAndBaseUrl(String baseUrl,String queryString){
18         return baseUrl + "?" + queryString;
19     }
20     
21     public static String buildUrlByQueryStringMapAndBaseUrl(String baseUrl,Map<String,String> map){
22         return buildUrlByQueryStringAndBaseUrl(baseUrl, buildQueryString(map));
23     }
24     
25     public static List<NameValuePair> buildNameValuePairs(Map<String,String> map){
26         Set<String> keySet = map.keySet();
27         List<NameValuePair> pairs = new ArrayList<NameValuePair>();
28         for(String key: keySet){
29             NameValuePair pair = new BasicNameValuePair(key, map.get(key));
30             pairs.add(pair);
31         }
32         return pairs;
33     }
34 }

 

(9)OAuthRequestTokenTask.java

 1 import oauth.signpost.OAuthConsumer;
 2 import oauth.signpost.OAuthProvider;
 3 import android.content.Context;
 4 import android.content.Intent;
 5 import android.net.Uri;
 6 import android.os.AsyncTask;
 7 
 8 public class OAuthRequestTokenTask extends AsyncTask<Void, Void, Void>{
 9 
10     private Context context;
11     private OAuthConsumer consumer;
12     private OAuthProvider provider;
13     
14     
15     public OAuthRequestTokenTask(Context context, OAuthConsumer consumer,
16             OAuthProvider provider) {
17         super();
18         this.context = context;
19         this.consumer = consumer;
20         this.provider = provider;
21     }
22 
23     @Override
24     protected Void doInBackground(Void... params) {
25         // TODO Auto-generated method stub
26         try {
27             System.out.println("请求Request Token之前" + consumer.getToken());
28             final String url = provider.retrieveRequestToken(consumer, Constants.OAUTH_CALLBACK_URL);
29             System.out.println("请求Request Toker之后" + consumer.getToken());
30             System.out.println("url---->" + url);
31             Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)).setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_NO_HISTORY | Intent.FLAG_FROM_BACKGROUND);
32             context.startActivity(intent);
33         } catch(Exception e) {
34             // TODO Auto-generated catch block
35             e.printStackTrace();
36         }
37         return null;
38     }
39 
40 }

 

(10)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 }

 

(11)RetrieveAccessTokenTask.java

 1 import oauth.signpost.OAuth;
 2 import oauth.signpost.OAuthConsumer;
 3 import oauth.signpost.OAuthProvider;
 4 import android.content.Context;
 5 import android.content.Intent;
 6 import android.content.SharedPreferences;
 7 import android.content.SharedPreferences.Editor;
 8 import android.net.Uri;
 9 import android.os.AsyncTask;
10 import android.util.Log;
11 
12 public class RetrieveAccessTokenTask extends AsyncTask<Uri, Void, Void> {
13 
14     final String TAG = "OAuth";
15     
16     private Context    context;
17     private OAuthProvider provider;
18     private OAuthConsumer consumer;
19     private SharedPreferences prefs;
20     
21     public RetrieveAccessTokenTask(Context context, OAuthConsumer consumer,OAuthProvider provider, SharedPreferences prefs) {
22         this.context = context;
23         this.consumer = consumer;
24         this.provider = provider;
25         this.prefs=prefs;
26     }
27 
28 
29     @Override
30     protected Void doInBackground(Uri...params) {
31         final Uri uri = params[0];
32         
33         System.out.println(getClass().getName());
34         
35         final String oauth_verifier = uri.getQueryParameter(OAuth.OAUTH_VERIFIER);
36 
37         try {
38             provider.retrieveAccessToken(consumer, oauth_verifier);
39 
40             final Editor edit = prefs.edit();
41             edit.putString(OAuth.OAUTH_TOKEN, consumer.getToken());
42             edit.putString(OAuth.OAUTH_TOKEN_SECRET, consumer.getTokenSecret());
43             edit.commit();
44             
45             String token = prefs.getString(OAuth.OAUTH_TOKEN, "");
46             String secret = prefs.getString(OAuth.OAUTH_TOKEN_SECRET, "");
47             
48             consumer.setTokenWithSecret(token, secret);
49             context.startActivity(new Intent(context,MainActivity.class));
50 
51             Log.i(TAG, "OAuth - Access Token Retrieved");
52             System.out.println("------------>" + provider.getAccessTokenEndpointUrl());
53             
54         } catch (Exception e) {
55             Log.e(TAG, "OAuth - Access Token Retrieval Error", e);
56         }
57 
58         return null;
59     }
60 }

 

 

 

 

ANDROID_MARS学习笔记_S04_005_用sing-post向腾讯微博发一条信息

标签:

原文地址:http://www.cnblogs.com/shamgod/p/5206505.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!