【问题标题】:Extract token from response string从响应字符串中提取令牌
【发布时间】:2013-04-20 13:49:29
【问题描述】:

如何从响应字符串中提取令牌? (不知道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);
        }

【问题讨论】:

    标签: ios oauth


    【解决方案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

    【讨论】:

      猜你喜欢
      • 2018-10-21
      • 2021-12-10
      • 2018-06-11
      • 2014-08-22
      • 2021-07-29
      • 1970-01-01
      • 2014-08-30
      • 2013-08-15
      • 2020-12-01
      相关资源
      最近更新 更多