如何让NSURLRequest获取Twitter请求令牌? [英] How to make NSURLRequest to obtain a Twitter request token?

查看:125
本文介绍了如何让NSURLRequest获取Twitter请求令牌?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用以下代码从Twitter获取请求令牌:

I am trying to obtain a request token from Twitter with this code:

NSMutableURLRequest *mURLRequest = [[NSMutableURLRequest alloc]initWithURL:[NSURL URLWithString:@"https://api.twitter.com/oauth/request_token"]];
mURLRequest.HTTPMethod = @"POST /oauth/request_token HTTP/1.1";
[mURLRequest setValue:@"User-Agent" forHTTPHeaderField:@"Coupled HTTP"];
[mURLRequest setValue:@"OAuth oauth_callback=\"http%3A%2F%2Fbytolution.com\"" forHTTPHeaderField:@"Authorization"];
[mURLRequest setValue:@"api.twitter.com" forHTTPHeaderField:@"Host"];
[mURLRequest setValue:@"Accept" forHTTPHeaderField:@"*/*"];

NSHTTPURLResponse *urlResponse;
NSError *error;
NSError *serializationError;
NSData *responseData = [NSURLConnection sendSynchronousRequest:mURLRequest returningResponse:&urlResponse error:&error];
NSLog(@"data: %@, response:%@, error: %@", [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&serializationError], urlResponse.allHeaderFields, error);

但我得到的全部是:

data:(null),response:{
Connection = close;
Content-Length= 0;
},错误:(null)

这里是Twitter关于此主题的文档。

Here is Twitter`s documentation for this topic.

感谢您的帮助!

推荐答案

经过两天的挫折和诅咒Twitter之后,我终于成功了。这是我的实施。用于发出请求的类是BL_TwitterRequest。这仅用于获取twitter请求令牌。

After two days of frustration and cursing Twitter, I finally managed to do this. Here is my implementation. The class which will be used to make the request is "BL_TwitterRequest". This is only for obtaining the twitter request token.

BL_TwitterRequest.h:

BL_TwitterRequest.h:

#import <Foundation/Foundation.h>

@interface BL_Request : NSObject <NSURLConnectionDelegate>

@property (nonatomic, strong) NSMutableData *webData;

-(void) makeRequest;

在实现类(BL_TwitterRequest.m)的顶部添加以下NSString类别。这将用于获取NSString的URL编码版本。

Add the following NSString category at the top of the implementation class (BL_TwitterRequest.m). This will be used to get the URL encoded version of NSString.

@implementation NSString (NSString_Extended)

- (NSString *)urlencode {
    NSMutableString *output = [NSMutableString string];
    const unsigned char *source = (const unsigned char *)[self UTF8String];
    int sourceLen = strlen((const char *)source);
    for (int i = 0; i < sourceLen; ++i) {
        const unsigned char thisChar = source[i];
        if (thisChar == ' '){
            [output appendString:@"+"];
        } else if (thisChar == '.' || thisChar == '-' || thisChar == '_' || thisChar == '~' ||
                   (thisChar >= 'a' && thisChar <= 'z') ||
                   (thisChar >= 'A' && thisChar <= 'Z') ||
                   (thisChar >= '0' && thisChar <= '9')) {
            [output appendFormat:@"%c", thisChar];
        } else {
            [output appendFormat:@"%%%02X", thisChar];
        }
    }
    return output;
}

@end

在添加以下功能 BL_TwitterRequest.m。它将用于生成oAuth nonce。该函数基本上生成一个指定长度的随机字符串。

Add the below function in "BL_TwitterRequest.m". It will be used to generate the oAuth nonce. The function basically generates a random string of a specified length.

-(NSString*) generateRandomStringOfLength:(int)length {

    NSString *letters = @"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    NSMutableString *randomString = [NSMutableString stringWithCapacity: length];
    for (int i = 0; i < length; i++) {
        [randomString appendFormat: @"%C", [letters characterAtIndex: arc4random() % [letters length]]];
    }

    return randomString;
}

包括这里。您只需将Base64.h和Base64.m文件拖到项目中即可。添加以下导入:

Include the Base64 library from here. All you have to do is drag the "Base64.h" and "Base64.m" files into your project. Add the following imports:

#include <CommonCrypto/CommonDigest.h>
#include <CommonCrypto/CommonHMAC.h>
#include <sys/types.h>
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#import "Base64.h"

添加另一个函数,如下所示。这将用于获取HMAC-SHA1值。

Add another function as specified below. This will be used to get the HMAC-SHA1 value.

- (NSString *)hmacsha1:(NSString *)data secret:(NSString *)key {

    const char *cKey  = [key cStringUsingEncoding:NSASCIIStringEncoding];
    const char *cData = [data cStringUsingEncoding:NSASCIIStringEncoding];

    unsigned char cHMAC[CC_SHA1_DIGEST_LENGTH];

    CCHmac(kCCHmacAlgSHA1, cKey, strlen(cKey), cData, strlen(cData), cHMAC);

    NSData *HMAC = [[NSData alloc] initWithBytes:cHMAC length:sizeof(cHMAC)];

    NSString *hash = [HMAC base64EncodedString];

    return hash;
}

现在是发出请求的主函数。

Now for the main function that will make the request.

-(void) makeRequest {

    _webData = [[NSMutableData alloc]init]; // WILL BE USED BY NSURLConnection

    NSString *httpMethod = @"POST";
    NSString *baseURL = @"https://api.twitter.com/oauth/request_token";
    NSString *oauthConsumerKey = @"YOUR_CONSUMER_KEY";
    NSString *oauthConsumerSecret = @"YOUR_CONSUMER_SECRET";
    NSString *oauth_timestamp = [NSString stringWithFormat:@"%.f", [[NSDate date]timeIntervalSince1970]];
    NSString *oauthNonce = [self generateRandomStringOfLength:42];
    NSString *oauthSignatureMethod = @"HMAC-SHA1";
    NSString *oauthVersion = @"1.0";
    NSString *oauthCallback = @"YOUR_TWITTER_CALLBACK_URL"; 

    //1. PERCENT CODE EVERY KEY AND VALUE THAT WILL BE SIGNED AND
    //   APPEND KEY AND VALUE WITH = AND &

    NSMutableString *parameterString = [[NSMutableString alloc]initWithFormat:@""];

    [parameterString appendFormat:@"oauth_callback=%@", [oauthCallback urlencode]];
    [parameterString appendFormat:@"&oauth_consumer_key=%@", [oauthConsumerKey urlencode]];
    [parameterString appendFormat:@"&oauth_nonce=%@", [oauthNonce urlencode]];
    [parameterString appendFormat:@"&oauth_signature_method=%@", [oauthSignatureMethod urlencode]];
    [parameterString appendFormat:@"&oauth_timestamp=%@", [oauth_timestamp urlencode]];
    [parameterString appendFormat:@"&oauth_version=%@", [oauthVersion urlencode]];

    //2. CREATE SIGNATURE STRING WITH HTTP METHOD AND ENCODED BASE URL AND PARAMETER STRING

    NSString *signatureBaseString = [NSString stringWithFormat:@"%@&%@&%@", httpMethod, [baseURL urlencode], [parameterString urlencode]];

    //3. GET THE SIGNING KEY NOW FROM CONSUMER SECRET

    NSString *signingKey = [NSString stringWithFormat:@"%@&", [oauthConsumerSecret urlencode]];

    //4. GET THE OUTPUT OF THE HMAC ALOGRITHM

    NSString *oauthSignature = [self hmacsha1:signatureBaseString secret:signingKey];

    // TIME TO MAKE THE CALL NOW

    NSMutableString *urlString = [[NSMutableString alloc]initWithFormat:@""];

    [urlString appendFormat:@"%@", baseURL];

    // INITIALIZE AUTHORIZATION HEADER

    NSMutableString *authHeader = [[NSMutableString alloc]initWithFormat:@""];

    [authHeader appendFormat:@"OAuth "]; // MIND THE SPACE AFTER 'OAuth'

    [authHeader appendFormat:@"oauth_nonce=\"%@\",", [oauthNonce urlencode]];
    [authHeader appendFormat:@"oauth_callback=\"%@\",", [oauthCallback urlencode]];
    [authHeader appendFormat:@"oauth_signature_method=\"%@\",", [oauthSignatureMethod urlencode]];
    [authHeader appendFormat:@"oauth_timestamp=\"%@\",", [oauth_timestamp urlencode]];
    [authHeader appendFormat:@"oauth_consumer_key=\"%@\",", [oauthConsumerKey urlencode]];
    [authHeader appendFormat:@"oauth_signature=\"%@\",", [oauthSignature urlencode]];
    [authHeader appendFormat:@"oauth_version=\"%@\"", [oauthVersion urlencode]];

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:[NSURL URLWithString:urlString]] ;

    [request setHTTPMethod:httpMethod];

    [request setValue:authHeader forHTTPHeaderField:@"Authorization"];

    NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];

    [connection start];

}

现在只需实现NSURLConnection委托方法即可获得响应。

Now just implement the NSURLConnection delegate methods to get the response.

#pragma mark - Connection Delegate

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {

    [_webData appendData:data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {

    NSString *resultString = [[NSString alloc]initWithData:_webData encoding:NSUTF8StringEncoding];

    NSLog(@"RESULT STRING : %@", resultString);  
}

如果一切顺利,'resultString'将包含oauth_token和oauth_token_secret。

If everything goes well the 'resultString' will have the oauth_token and oauth_token_secret.

要拨打电话,请执行以下操作:

To make the call just do the following:

 BL_TwitterRequest *twitterRequest = [[BL_TwitterRequest alloc]init];
 [twitterRequest makeRequest];

请记住,任何遗漏的空格或逗号都可能导致错误。

Remember any missed spaces or commas can result in an error.

这篇关于如何让NSURLRequest获取Twitter请求令牌?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆