Home Database Mysql Tutorial IOS最新新浪微博开放平台Oauth2.0授权获取Access

IOS最新新浪微博开放平台Oauth2.0授权获取Access

Jun 07, 2016 pm 03:49 PM
ios platform open Weibo Authorize Sina up to date

很久没写博客,最近在搞一个新浪微博的第三方应用,涉及到了Oauth2.0授权获取Access_Token,特此记录分享! 步骤一:添加应用 进入新浪微博开放平台(没有的话自行注册),进入“管理中心“,点击”创建应用”,选择“微链接应用”,再点击“创建应用”,,

很久没写博客,最近在搞一个新浪微博的第三方应用,涉及到了Oauth2.0授权获取Access_Token,特此记录分享!

步骤一:添加应用

进入新浪微博开放平台(没有的话自行注册),进入“管理中心“,点击”创建应用”,选择“微链接应用”,再点击“创建应用”,,选“移动应用”,填写相应的信息,其中应用地址没有的话可随便,勾选平台后提交。注意保存你的App Key和App Secret以备后用。

步骤二:Oauth2.0授权设置

应用创建完后可以在“管理中心”-“我的应用”中查看信息,在“应用信息”--“高级信息”中可以设置网站的授权回调页和取消授权回调页。授权回调页会在用户授权成功后会被回调,同时传回一个“code”参数,开发者可以用code换取Access_Token值。当然如果是移动应用,比如本文是没有自己授权回调页的,建议这里填:https://api.weibo.com/oauth2/default.html 或者 http://www.baidu.com 之类的。如果授权后传回的形式如下:

https://api.weibo.com/oauth2/default.html?code=a6146547f981199c07348837b0629d5d

我们只要获取其中code的值a6146547f981199c07348837b0629d5d即可,注意code的值每次都是不一样的。

步骤三:引导用户授权

引导需要授权的用户到如下页面:
https://api.weibo.com/oauth2/authorize?client_id=YOUR_CLIENT_ID&response_type=code&redirect_uri=YOUR_REGISTERED_REDIRECT_URI
YOUR_CLIENT_ID:即应用的AppKey,可以在应用基本信息里查看到。
YOUR_REGISTERED_REDIRECT_URI:即之前填写的授权回调页,注意一定要和你在开发平台填写的完全相同,这里以https://api.weibo.com/oauth2/default.html 为例。
如果用户授权成功后,会跳转到回调页,开发者此时需要得到url参数中的code值,注意code只能使用一次。

步骤四:换取Access Token

开发者可以访问如下页面得到Access Token:
https://api.weibo.com/oauth2/access_token?client_id=YOUR_CLIENT_ID&client_secret=YOUR_CLIENT_SECRET&grant_type=authorization_code&redirect_uri=YOUR_REGISTERED_REDIRECT_URI&code=CODE
YOUR_CLIENT_ID:即应用的AppKey,可以在应用基本信息里查看到。
YOUR_CLIENT_SECRET:即应用的App Secret,可以在应用基本信息里查看到。
YOUR_REGISTERED_REDIRECT_URI:即之前填写的授权回调页
code:就是步骤三引导用户授权后回传的code。
如果都没有问题,就可以得到Access Token了,返回示例:
{
       "access_token": "ACCESS_TOKEN",
       "expires_in": 1234,
       "remind_in":"798114",
       "uid":"12341234"
 }


最后做了一个Xcode 5.0 storyboard的demo,用到一个UIViewController和一个UIWebView。

看代码如下:

#import <uikit>

@interface OAuthWebViewController : UIViewController<uiwebviewdelegate>

@property (weak, nonatomic) IBOutlet UIWebView *webView;

@end</uiwebviewdelegate></uikit>
Copy after login

#import "OAuthWebViewController.h"

@implementation OAuthWebViewController
@synthesize webView;

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    NSString *url = @"https://api.weibo.com/oauth2/authorize?client_id=3693781153&redirect_uri=https://api.weibo.com/oauth2/default.html&response_type=code&display=mobile";
    
    NSURLRequest *request = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:url]];
    [self.webView setDelegate:self];
    [self.webView loadRequest:request];

}

-(void)viewDidLoad
{
    [super viewDidLoad];
}

#pragma mark - UIWebView Delegate Methods

-(void)webViewDidFinishLoad:(UIWebView *)_webView
{
    NSString *url = _webView.request.URL.absoluteString;
    NSLog(@"absoluteString:%@",url);
    
    if ([url hasPrefix:@"https://api.weibo.com/oauth2/default.html?"]) {
        
        //找到”code=“的range
        NSRange rangeOne;
        rangeOne=[url rangeOfString:@"code="];
        
        //根据他“code=”的range确定code参数的值的range
        NSRange range = NSMakeRange(rangeOne.length+rangeOne.location, url.length-(rangeOne.length+rangeOne.location));
        //获取code值
        NSString *codeString = [url substringWithRange:range];
        NSLog(@"code = :%@",codeString);
        
        //access token调用URL的string
        NSMutableString *muString = [[NSMutableString alloc] initWithString:@"https://api.weibo.com/oauth2/access_token?client_id=3693781153&client_secret=7954135ee119b1fd068b8f41d2de5672&grant_type=authorization_code&redirect_uri=https://api.weibo.com/oauth2/default.html&code="];
        [muString appendString:codeString];
        NSLog(@"access token url :%@",muString);
        
        //第一步,创建URL
        NSURL *urlstring = [NSURL URLWithString:muString];
        //第二步,创建请求
        NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:urlstring cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];
        [request setHTTPMethod:@"POST"];//设置请求方式为POST,默认为GET
        NSString *str = @"type=focus-c";//设置参数
        NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
        [request setHTTPBody:data];
        //第三步,连接服务器
        NSData *received = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
        
        NSString *str1 = [[NSString alloc]initWithData:received encoding:NSUTF8StringEncoding];
        NSLog(@"Back String :%@",str1);
        
        NSError *error;
        //如何从str1中获取到access_token
        NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:received options:NSJSONReadingMutableContainers error:&error];
        
        NSString *_access_token = [dictionary objectForKey:@"access_token"];
        NSLog(@"access token is:%@",_access_token);
        
    }
}

@end
Copy after login

来几张图:

IOS最新新浪微博开放平台Oauth2.0授权获取Access

IOS最新新浪微博开放平台Oauth2.0授权获取Access

IOS最新新浪微博开放平台Oauth2.0授权获取Access


demo下载地址:http://download.csdn.net/detail/wangqiuyun/6851621

注意替换为你的AppKey和App Secret。

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)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks 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)

The first version of Apple's iOS 18 was exposed to have so many bugs: serious fever, WeChat delay The first version of Apple's iOS 18 was exposed to have so many bugs: serious fever, WeChat delay Jun 13, 2024 pm 09:39 PM

The annual WWDC has ended, and iOS18 is undoubtedly the focus of everyone's attention. Currently, many iPhone users are rushing to upgrade to iOS18, but various system bugs are making people uncomfortable. Some bloggers said that you should be cautious when upgrading to iOS18 because "there are so many bugs." The blogger said that if your iPhone is your main machine, it is recommended not to upgrade to iOS18 because the first version has many bugs. He also summarized several system bugs currently encountered: 1. Switching icon style is stuck, causing the icon not to be displayed. 2. Flashlight width animation is often lost. 3. Douyin App cannot upload videos. 4. WeChat message push is delayed by about 10 seconds. 5 . Occasionally, the phone cannot be made and the screen is black. 6. Severe fever.

Apple releases open source Swift package for homomorphic encryption, deployed in iOS 18 Apple releases open source Swift package for homomorphic encryption, deployed in iOS 18 Jul 31, 2024 pm 01:10 PM

According to news on July 31, Apple issued a press release yesterday (July 30), announcing the launch of a new open source Swift package (swift-homomorphic-encryption) for enabling homomorphic encryption in the Swift programming language. Note: Homomorphic Encryption (HE) refers to an encryption algorithm that satisfies the homomorphic operation properties of ciphertext. That is, after the data is homomorphically encrypted, specific calculations are performed on the ciphertext, and the obtained ciphertext calculation results are processed at the same time. The plaintext after state decryption is equivalent to directly performing the same calculation on the plaintext data, achieving the "invisibility" of the data. Homomorphic encryption technology can calculate encrypted data without leaking the underlying unencrypted data to the operation process.

Apple re-releases iOS/iPadOS 18 Beta 4 update, version number raised to 22A5316k Apple re-releases iOS/iPadOS 18 Beta 4 update, version number raised to 22A5316k Jul 27, 2024 am 11:06 AM

Thanks to netizens Ji Yinkesi, xxx_x, fried tomatoes, Terrence, and spicy chicken drumsticks for submitting clues! According to news on July 27, Apple today re-released the iOS/iPadOS 18 Beta 4 update for developers. The internal version number was upgraded from 22A5316j to 22A5316k. It is currently unclear the difference between the two Beta 4 version updates. Registered developers can open the "Settings" app, enter the "Software Update" section, click the "Beta Update" option, and then toggle the iOS18/iPadOS18 Developer Beta settings to select the beta version. Downloading and installing the beta version requires an Apple ID associated with a developer account. Reported on July 24, iO

Update | Hacker explains how to install Epic Games Store and Fortnite on iPad outside the EU Update | Hacker explains how to install Epic Games Store and Fortnite on iPad outside the EU Aug 18, 2024 am 06:34 AM

Update: Saunders Tech has uploaded a tutorial to his YouTube channel (video embedded below) explaining how to install Fortnite and the Epic Games Store on an iPad outside the EU. However, not only does the process require specific beta versions of iO

New features of Apple's iOS 18 'Boundless Notes” app: expanded Scenes functionality, introduced grid alignment New features of Apple's iOS 18 'Boundless Notes” app: expanded Scenes functionality, introduced grid alignment Jun 02, 2024 pm 05:05 PM

According to news on June 1, technology media AppleInsider published a blog post today, stating that Apple will launch a new navigation function of "Scenes" for the "Freeform" application extension in the iOS18 system, and add new options for object alignment. Introduction to the "Wubianji" application First, let's briefly introduce the "Wubianji" application. The application will be launched in 2022 and has currently launched iOS, iPadOS, macOS15 and visionOS versions. Apple’s official introduction is as follows: “Boundless Notes” is an excellent tool for turning inspiration into reality. Sketch projects, design mood boards, or start brainstorming on a flexible canvas that supports nearly any file type. With iCloud, all your boards

Apple iOS/iPadOS 18 Developer Preview Beta 4 released: Added CarPlay wallpapers, sorted out settings options, enhanced camera control Apple iOS/iPadOS 18 Developer Preview Beta 4 released: Added CarPlay wallpapers, sorted out settings options, enhanced camera control Jul 24, 2024 am 09:54 AM

Thanks to netizens Spicy Chicken Leg Burger, Soft Media New Friends 2092483, Handwritten Past, DingHao, Xiaoxing_14, Wowotou Eat Big Kou, Feiying Q, Soft Media New Friends 2168428, Slades, Aaron212, Happy Little Hedgehog, Little Earl, Clues for the little milk cat that eats fish! [Click here to go directly to the upgrade tutorial] According to news on July 24, Apple today pushed the iOS/iPadOS18 developer preview version Beta4 update (internal version number: 22A5316j) to iPhone and iPad users. This update is 15 days after the last release. . Carplay Wallpaper Apple has added wallpapers to CarPlay, covering light and dark modes. Its wallpaper style is similar to iPhone

Apple iOS 17.5 RC version released: allows EU iPhone users to download apps from the website Apple iOS 17.5 RC version released: allows EU iPhone users to download apps from the website May 08, 2024 am 09:30 AM

[Click here to go directly to the upgrade tutorial] According to news on May 8, Apple pushed the iOS17.5RC update (internal version number: 21F79) to iPhone users today. This update is 70 days away from the last release. How to upgrade iOS/iPadOS/watchOS/macOS development version and public beta version? To upgrade the iOS/iPadOS17 developer preview version and public beta version, you can refer to the experience shared by friends: Experience Post 1||Experience Post 2||Experience Post 3||Experience Post 4. Starting from the iOS/iPadOS 16.4 Developer Preview Beta 1, you need to register for the Apple Developer Program. After registration, open the system [Settings] [Software Update] to see the upgrade option. Please note that your iPhone or IP

Apple releases iOS/iPadOS 16.7.9 and 15.8.3 updates to older iPhones/iPads: fix security vulnerabilities Apple releases iOS/iPadOS 16.7.9 and 15.8.3 updates to older iPhones/iPads: fix security vulnerabilities Jul 30, 2024 am 10:13 AM

Thanks to netizen Ji Yinkesi for submitting the clue! According to news on July 30, Apple today released the first developer beta version of iOS/iPadOS 18.1 and the second public beta version of iOS/iPadOS 18. It also released iOS 16.7.9 and iOS 15.8.3 updates for older iPhones. Apple wrote in the update logs for both versions: "This update provides important security fixes and is recommended for all users to install," but did not mention what was fixed. iOS16.7.9 Note: iOS16.7.9 is suitable for Apple iPhoneX, iPhone8 and iPhone8Plus. According to the document details disclosed by Apple, the above three models are expected to support

See all articles