如何使用OAuth和NSURLRequest从Twitter获取请求令牌?

时间:2013-02-17 19:15:33

标签: objective-c twitter oauth

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

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

NSURL *requestTokenURL = [NSURL URLWithString:@"https://api.twitter.com/oauth/request_token"];
NSInteger numberOfSecs = round([[NSDate date]timeIntervalSince1970]);
NSString *timestampString = [NSString stringWithFormat:@"%i", numberOfSecs];

NSMutableDictionary *signingParams = [[NSMutableDictionary alloc]initWithCapacity:10];
[signingParams setObject:@"xxxxxxxxxxxxxxx" forKey:@"oauth_consumer_key"];
[signingParams setObject:[nonce copy] forKey:@"oauth_nonce"];
[signingParams setObject:@"HMAC-SHA1" forKey:@"oauth_signature_method"];
[signingParams setObject:timestampString forKey:@"oauth_timestamp"];
[signingParams setObject:@"1.0" forKey:@"oauth_version"];

NSMutableURLRequest *mURLRequest = [[NSMutableURLRequest alloc]initWithURL:requestTokenURL];
mURLRequest.HTTPMethod = @"POST";
NSString *callbackURLString = @"http://bytolution.com";
//that is one fat piece of code...
NSString *authenticationHeaderString = [NSString stringWithFormat:@"OAuth oauth_callback=\"%@\", oauth_nonce=\"%@\", oauth_signature_method=\"HMAC-SHA1\", oauth_timestamp=\"%@\", oauth_consumer_key=\"xxxxxxxxxxxxxxxxx\", oauth_signature=\"%@\", oauth_version=\"1.0\"", [callbackURLString URLEncodedString], nonce, timestampString, [BYOAuthSignatureString signatureStringWithParameters:signingParams URL:[mURLRequest.URL absoluteString] HTTPMethod:mURLRequest.HTTPMethod]];

[mURLRequest setValue:authenticationHeaderString forHTTPHeaderField:@"Authorization"];


NSHTTPURLResponse *urlResponse;
NSError *error;
NSData *responseData = [NSURLConnection sendSynchronousRequest:mURLRequest returningResponse:&urlResponse error:&error];
NSString *dataString = [[NSString alloc]initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(@"data: %@, response:%@, error: %@", dataString , urlResponse.allHeaderFields, error);

BYOAuthSignatureString创建签名以签署请求,并检查了请求的所有参数。他们应该根据Twitter的文档工作。

Creating a signature

Implementing Sign-in with Twitter

但我的记录说

data: Failed to validate oauth signature and token, response:(null), error: Error Domain=NSURLErrorDomain Code=-1012 "The operation couldn’t be completed. (NSURLErrorDomain error -1012.)" UserInfo=0x20892200 {NSErrorFailingURLKey=https://api.twitter.com/oauth/request_token, NSErrorFailingURLStringKey=https://api.twitter.com/oauth/request_token, NSUnderlyingError=0x20891ac0 "The operation couldn’t be completed. (kCFErrorDomainCFNetwork error -1012.)"}

感谢您的帮助!

0 个答案:

没有答案