3

我正在尝试使用以下代码从 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 的文档工作。

创建签名

使用 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.)"}

谢谢你的帮助!

4

0 回答 0