Home Database Mysql Tutorial 关于新浪微博与腾讯微博从Oauth1.0升级到Oauth2.0的过程

关于新浪微博与腾讯微博从Oauth1.0升级到Oauth2.0的过程

Jun 07, 2016 pm 03:27 PM
oauth2 about upgrade Weibo Sina Tencent

下载地址~ http://download.csdn.net/detail/zhangnianxiang/4375685 新浪微博 曾经@微博API 新浪那边表示 旧版的Oauth 1.0a将在不久的2012.9.1号停止。这个是一个很苦的消息。意味着涉及微博的都要修改。 Oauth2.0相比较于Oauth1.0的话 流程少了很多,其中

下载地址~

http://download.csdn.net/detail/zhangnianxiang/4375685



新浪微博

曾经@微博API 新浪那边表示 旧版的Oauth 1.0a将在不久的2012.9.1号停止。这个是一个很苦逼的消息。意味着涉及微博的都要修改。

Oauth2.0相比较于Oauth1.0的话  流程少了很多,其中一点就是签名。之前都是用signpost这个开源项目辅助。现在完全可以去掉了


好吧。废话不说了。 

新浪微博Oauth2.0认证的官方说明

http://open.weibo.com/wiki/Oauth2


简单步骤:1获取code 2获取accessToken 3使用accessToken访问api

新浪的这份授权机制还是比较详细。理解起来比较容易

接口 说明
OAuth2/authorize 请求用户授权Token
OAuth2/access_token 获取授权过的Access Token
OAuth2/get_oauth2_token  OAuth1.0的Access Token更换至OAuth2.0的Access Token

  步骤1http://open.weibo.com/wiki/Oauth2/authorize

获取code

请求参数

  必选 类型及范围 说明
client_id true string 申请应用时分配的AppKey。
redirect_uri true string 授权回调地址,站外应用需与设置的回调地址一致,站内应用需填写canvas page的地址。
response_type false string 返回类型,支持code、token,默认值为code。
state false string 用于保持请求和回调的状态,在回调时,会在Query Parameter中回传该参数。
display false string 授权页面的终端类型,取值见下面的说明。


https://api.weibo.com/oauth2/authorize?client_id=YOUR_CLIENT_ID&response_type=code&redirect_uri=YOUR_REGISTERED_REDIRECT_URI
Copy after login

值得注意的是这边的redirect_uri  必须与   申请的应用那边设置(高级设置里面)的回调地址一致。否则就会出现 error:redirect_uri_mismatch.

这是网页载入授权界面,用户填完账号密码之后按下确定
服务器将返回一个“回调地址+code=xxxxx”的URL(如果是腾讯微博还有openid和openkey等等)
把code是步骤2的关键

步骤2
获取accessToken

API  https://api.weibo.com/oauth2/access_token
将code等参数 以POST传给服务器将返回

 {
       "access_token": "ACCESS_TOKEN",
       "expires_in": 1234,
       "remind_in":"798114",
       "uid":"12341234"
 }
Copy after login

这些数据都是要做数据持久化管理的。
腾讯微博返回稍有不同,但是并不影响

步骤3
访问API



研究中遇到的一些问题
1.腾讯微博    那群脑残的腾讯微博把appke和secret变成  ClientID和ClientSecret

oAuth.setClientId(StatcParame.T_CONSUMER_KEY);
oAuth.setClientSecret(StatcParame.T_CONSUMER_SECRET);

下面直接贴源码了

1
sina
webview承载授权页面的设置
		web=(WebView)findViewById(R.id.web);
		web.getSettings().setJavaScriptEnabled(true);
		web.getSettings().setSupportZoom(true);
		web.getSettings().setBuiltInZoomControls(true);
		web.setWebViewClient(new WebViewC()); 
Copy after login
WebviewClient
Copy after login
class WebViewC extends WebViewClient{
		@Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
	        super.onPageStarted(view, url, favicon);
	        Log.v("aaa", "===onPageStarted==="+url);
			 if(url.contains("code=")){
					try {
						Intent intent = new Intent(Oauth2Activity.this,MainActivity.class);
					 	Uri uri = Uri.parse(url);
						String code = uri.getQueryParameter("code");
						String openid =uri.getQueryParameter("openid");
						String openkey=uri.getQueryParameter("openkey");
						editor.putString(StatcParame.T_OPEN_ID, openid);
						editor.putString(StatcParame.T_OPEN_KEY, openkey);
						HttpClient httpclient=MyCountHttpClient.getNewHttpClient();
						URI accessToken = null;
						List<namevaluepair> parameters=new ArrayList<namevaluepair>();
						//必须编码,否则无法向服务器发送微博
						if(codeFlag==1){
							parameters.add(new BasicNameValuePair("client_id", StatcParame.S_CONSUMER_KEY));
							parameters.add(new BasicNameValuePair("client_secret", StatcParame.S_CONSUMER_SECRET));
							parameters.add(new BasicNameValuePair("redirect_uri", StatcParame.S_CALLBACK));
							
							accessToken = URI.create(StatcParame.S_API_access_token);
							intent.putExtra("mode", 1);
						}else if(codeFlag ==2){
							parameters.add(new BasicNameValuePair("client_id", StatcParame.T_CONSUMER_KEY));
							parameters.add(new BasicNameValuePair("client_secret", StatcParame.T_CONSUMER_SECRET));
							parameters.add(new BasicNameValuePair("redirect_uri", StatcParame.T_CALLBACK));
							
							accessToken = URI.create(StatcParame.T_API_access_token);
							
							intent.putExtra("mode", 2);
						}
						parameters.add(new BasicNameValuePair("grant_type", "authorization_code"));
						parameters.add(new BasicNameValuePair("code", code));
						
						
						HttpPost post=new HttpPost(accessToken);
						HttpResponse response=null;
				
						post.setEntity(new UrlEncodedFormEntity(parameters ,HTTP.UTF_8) );
						post.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false);
						
						 response = httpclient.execute(post);
						 if(codeFlag==1){
							 JSON.GetOauth(sharedpre,Utils.getResponseText(response));
						 }else if(codeFlag==2){
							 String tempUrl = StatcParame.T_CALLBACK+"?"+Utils.getResponseText(response);
							 Uri temp = Uri.parse(tempUrl);
							 String access_token = temp.getQueryParameter("access_token");
							 String expires_in=temp.getQueryParameter("expires_in");
							 String name=temp.getQueryParameter("name");
							 editor.putString(StatcParame.T_ACCESS_TOKEN, access_token);
							 editor.putString(StatcParame.T_EXPIRES_IN, expires_in);
							 editor.putString(StatcParame.T_NAME, name);
							 editor.commit();
						 }
						 startActivity(intent);
						 Oauth2Activity.this.finish();
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
			 }
        }
	}
</namevaluepair></namevaluepair>
Copy after login

这个方法集合了sina和tencent的处理

这步走完就拿到ACCESSTOKEN了


下面贴个发布微博的方法


SINA发送一个带图片的微博

<span>Weibo weibo = Weibo.getInstance();
			AccessToken accessToken = new AccessToken(shared.getString(StatcParame.S_ACCESS_TOKEN, ""), StatcParame.S_CONSUMER_SECRET);
			accessToken.setExpiresIn(shared.getString(StatcParame.S_EXPIRES_IN, ""));
			weibo.setAccessToken(accessToken);
			weibo.setupConsumerConfig(StatcParame.S_CONSUMER_KEY, StatcParame.S_CONSUMER_SECRET);
			weibo.setRedirectUrl("http://www.sina.com.cn");

			try {
				String msg = URLEncoder.encode(body, HTTP.UTF_8);
			
			        WeiboParameters bundle = new WeiboParameters();
			        bundle.add("status", msg);
			        bundle.add("pic", "/sdcard/1.jpg");
			        String rlt = "";
			        String url = Weibo.SERVER + "statuses/upload.json";
			        
			        Utility.setAuthorization(new Oauth2AccessTokenHeader());
			        rlt = weibo.request(context, url, bundle, Utility.HTTPMETHOD_POST, weibo.getAccessToken());

				Toast.makeText(context, rlt, 1000).show();
				Log.v("aaa","Successfully upload the status to ["+ rlt+ "].");
					return "OK";
			} catch (Exception e1) {
				e1.printStackTrace();
			}</span>
Copy after login


TENCent发送一条微博

OAuthV2 oAuth =new OAuthV2();
		oAuth.setAccessToken(shared.getString(StatcParame.T_ACCESS_TOKEN, ""));
		oAuth.setOauthVersion("2.a");
		oAuth.setClientIP("117.25.173.11");
		oAuth.setOpenid(shared.getString(StatcParame.T_OPEN_ID, ""));
		oAuth.setOpenkey(shared.getString(StatcParame.T_OPEN_KEY, ""));
		oAuth.setClientId(StatcParame.T_CONSUMER_KEY);
		oAuth.setClientSecret(StatcParame.T_CONSUMER_SECRET);
		

		try {
			TAPI api = new TAPI("2.a");
			String respone = api.add(oAuth, "json","abcc","117.25.173.11","","","0");
			Toast.makeText(context, respone, 1000).show();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
Copy after login


源码之后上传。

联系 zhangnianxiang@gmail.com


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to search previous Weibo by date on Weibo_How to search previous Weibo by date on Weibo How to search previous Weibo by date on Weibo_How to search previous Weibo by date on Weibo Mar 30, 2024 pm 07:26 PM

1. First open the mobile web browser, search for the Weibo web version, and click the avatar button in the upper left corner after entering. 2. Then click Settings in the upper right corner. 3. Click the version switching option in settings. 4. Then select the color version option in the version switch. 5. Click Search to enter the search page. 6. After entering the keywords, click Find People. 7. When the search completion interface appears, click Filter. 8. Finally, enter the specific date in the release time column and click Filter.

Big model app Tencent Yuanbao is online! Hunyuan is upgraded to create an all-round AI assistant that can be carried anywhere Big model app Tencent Yuanbao is online! Hunyuan is upgraded to create an all-round AI assistant that can be carried anywhere Jun 09, 2024 pm 10:38 PM

On May 30, Tencent announced a comprehensive upgrade of its Hunyuan model. The App "Tencent Yuanbao" based on the Hunyuan model was officially launched and can be downloaded from Apple and Android app stores. Compared with the Hunyuan applet version in the previous testing stage, Tencent Yuanbao provides core capabilities such as AI search, AI summary, and AI writing for work efficiency scenarios; for daily life scenarios, Yuanbao's gameplay is also richer and provides multiple features. AI application, and new gameplay methods such as creating personal agents are added. "Tencent does not strive to be the first to make large models." Liu Yuhong, vice president of Tencent Cloud and head of Tencent Hunyuan large model, said: "In the past year, we continued to promote the capabilities of Tencent Hunyuan large model. In the rich and massive Polish technology in business scenarios while gaining insights into users’ real needs

How to release someone blocked on Weibo_How to unblock Weibo How to release someone blocked on Weibo_How to unblock Weibo Mar 30, 2024 am 09:51 AM

1. Click [My] in the lower right corner of the Weibo app to enter your personal homepage. 2. Then, click the gear icon in the upper right corner. 3. At this time, we enter the settings page, select [Block Settings] here to enter. 4. In the blocking settings, we can see the friends we have blocked, tap it, and click [Unblock] in the pop-up options. 5. Or users can directly search Weibo users to enter the blocked user homepage, and click [...] on the upper right to remove the blacklist.

How to delete the draft box of 'Weibo'_Tutorial on deleting the draft box of 'Weibo' How to delete the draft box of 'Weibo'_Tutorial on deleting the draft box of 'Weibo' Mar 30, 2024 pm 12:46 PM

1. First open Weibo, click on My, and click on the draft box. 2. Then long press any draft and click to clear the draft box or delete the draft. 3. Finally click OK.

How to turn off Weibo live mode_How to turn off Weibo live mode How to turn off Weibo live mode_How to turn off Weibo live mode Mar 30, 2024 am 10:16 AM

1. First open Weibo, click Search, and click More Hot Searches. 2. Then select a hot search to enter. 3. Then enter the hot search comment live mode, find and click the standard version in the upper right corner. 4. Finally, you can return to the hot search standard comment area. If you want to continue viewing the live comment area, click the live version in the upper right corner. Note: Only when there are a lot of real-time comments will it automatically enter the live mode. Some hot searches will automatically enter the live mode. Generally, hot searches are in standard mode.

How to post videos on Weibo without compressing the image quality_How to post videos on Weibo without compressing the image quality How to post videos on Weibo without compressing the image quality_How to post videos on Weibo without compressing the image quality Mar 30, 2024 pm 12:26 PM

1. First open Weibo on your mobile phone and click [Me] in the lower right corner (as shown in the picture). 2. Then click [Gear] in the upper right corner to open settings (as shown in the picture). 3. Then find and open [General Settings] (as shown in the picture). 4. Then enter the [Video Follow] option (as shown in the picture). 5. Then open the [Video Upload Resolution] setting (as shown in the picture). 6. Finally, select [Original Image Quality] to avoid compression (as shown in the picture).

If Weibo svip deletes visitor records, can the other party still see it? If Weibo svip deletes visitor records, can the other party still see it? Apr 02, 2024 am 08:04 AM

Once Weibo users activate the SVIP function, they can manage visitor records, and if they visit a stranger's homepage, they can delete it before displaying it, so that they do not know that they are browsing the homepage. ?Can the other party still see it after deleting the visitor record on Weibo svip? Can the other party still see it after deleting the visitor record on Weibo svip? 1. After deleting the visitor record on svip, the other party cannot see it. It will only see the increase in the number of visitors, but it will not show the visitors. The user's ID and avatar. 2. Ordinary users and VIP users cannot delete or view access records. They can only see how many people have visited them. 3. Weibo access data will be updated at 8:00 every day. If you want to delete access records, you need to

Xiaoyi upgraded to an intelligent agent! HarmonyOS NEXT Hongmeng native intelligence opens a new AI era Xiaoyi upgraded to an intelligent agent! HarmonyOS NEXT Hongmeng native intelligence opens a new AI era Jun 22, 2024 am 01:56 AM

On June 21, Huawei Developer Conference 2024 (HDC2024) gathered again in Songshan Lake, Dongguan. At this conference, the most eye-catching thing is that HarmonyOSNEXT officially launched Beta for developers and pioneer users, and comprehensively demonstrated the three "king-breaking" innovative features of HarmonyOSNEXT in all scenarios, native intelligence and native security. HarmonyOSNEXT native intelligence: Opening a new AI era After abandoning the Android framework, HarmonyOSNEXT has become a truly independent operating system independent of Android and iOS, which can be called an unprecedented rebirth. Among its many new features, native intelligence is undoubtedly the new feature that can best bring users intuitive feelings and experience upgrades.

See all articles