如何使NSURLRequest获取Twitter请求令牌?

时间:2013-02-16 18:11:05

标签: objective-c http twitter nsurlrequest

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

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; }, error: (null)

Here是Twitter关于此主题的文档。

感谢您的帮助!

2 个答案:

答案 0 :(得分:2)

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

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编码版本。

@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。该函数基本上生成一个指定长度的随机字符串。

-(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;
}

包括here中的Base64库。您所要做的就是将“Base64.h”和“Base64.m”文件拖到项目中。添加以下导入:

#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值。

- (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;
}

现在提供请求的主要功能。

-(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委托方法即可获得响应。

#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。

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

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

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

答案 1 :(得分:1)

多个错误(不确定列表是否完整,这是我第一眼看到的):

  • HTTP方法应该只是@"POST",而不是@"POST foo"@"POST or I will kill you"或其他任何内容;
  • 同样,@"OAuth oauth_callback=\""应为@"oauth_callback=\"";
  • 您未包含所有必需的标题字段,例如oauth_consumer_keyoauth_signatureoauth_signature_methodoauth_nonceoauth_timestamp;
  • 这不会返回JSON。它返回一个URL编码的响应,类似于official documentation
  • 中的示例