0

如何从响应字符串中提取令牌?(不知道token的长度,所以这里不能使用NSRange)

oauth_callback_confirmed=true&oauth_token=72157632316931441
-fadcd6ef70cbd06c&oauth_token_secret=a7e7b046a8960559

当前代码是(它给出了令牌和字符串的其余部分):

NSRange access_token_range = [operation.responseString rangeOfString:@"oauth_token="];
        if (access_token_range.length > 0) {
            int from_index = access_token_range.location + access_token_range.length;
            NSString *access_token = [operation.responseString substringFromIndex:from_index];

            NSLog(@"access_token:  %@", access_token);
        }
4

1 回答 1

1

最好(更优雅)将响应字符串分离为键值对,然后分别处理它们:

NSString *token = nil;
NSArray *kvpairs = [operation.responseString componentsSeparatedByString:@"&"];
for (NSString *kvpair in kvpairs) {
    NSArray *keyAndValue = [kvpair componentsSeparatedByString:@"="];
    NSString *key = [keyAndValue objectAtIndex:0];
    if ([key isEqualToString:@"oauth_token"]) {
        token = [keyAndValue objectAtIndex:1];
        break;
    }
}

现在token将包含令牌,或者nil如果找不到它。

于 2012-12-23T13:57:22.683 回答