如何使的NSURLRequest获得Twitter的请求令牌?(How to make NSURLR

2019-07-20 01:26发布

我试图从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)

下面是这个话题Twitter`s文档。

谢谢你的帮助!

Answer 1:

经过挫折和咒骂的Twitter的两天,我终于成功地做到这一点。 下面是我的实现。 这将被用来制造该请求的类是“BL_TwitterRequest”。 这仅仅是用于获取Twitter的请求令牌。

BL_TwitterRequest.h:

#import <Foundation/Foundation.h>

@interface BL_Request : NSObject <NSURLConnectionDelegate>

@property (nonatomic, strong) NSMutableData *webData;

-(void) makeRequest;

添加以下的NSString类的实现类(BL_TwitterRequest.m)的顶部。 这将被用来获得的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的认证随机数。 功能基本上产生指定长度的随机串。

-(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编码库在这里 。 所有你需要做的就是拖“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];

记住错过任何空格或会导致错误的逗号。



Answer 2:

多个错误(不知道该列表是完整的,这是我第一眼发现的):

  • 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编码的响应,如在例如一些官方文件 。


文章来源: How to make NSURLRequest to obtain a Twitter request token?