首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >NSURLConnection授权头不起作用

NSURLConnection授权头不起作用
EN

Stack Overflow用户
提问于 2013-09-19 11:03:53
回答 3查看 9.3K关注 0票数 20

我试图通过NSURLConnection在HTTP头中发送一个OAuth访问令牌,但它似乎没有发送这个头,因为API一直给我一个错误,告诉我“必须提供授权令牌”。

这是我使用的代码:

NSURL *aUrl = [NSURL URLWithString: @"http://generericfakeapi.com/user/profile"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:aUrl
                                                       cachePolicy:NSURLRequestUseProtocolCachePolicy
                                                   timeoutInterval:30.0];

[request addValue:[NSString stringWithFormat:@"OAuth %@", token] forHTTPHeaderField:@"Authorization"];

[request setHTTPMethod:@"GET"];

NSError *error = nil;
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error: &error];

NSDictionary *JSONDictionary = [NSJSONSerialization JSONObjectWithData:returnData options:kNilOptions error:&error];
NSLog(@"Response : %@", JSONDictionary);

下面是该接口的cURL命令示例:

curl 'http://generericfakeapi.com/user/profile' -H 'Authorization: OAuth YourAuthToken'

这不就是我通过NSURLConnection所做的吗?

任何帮助都将不胜感激。

EN

回答 3

Stack Overflow用户

发布于 2014-04-15 15:34:22

更改此行:

NSURL *aUrl = [NSURL URLWithString: @"http://generericfakeapi.com/user/profile"];

至:

NSURL *aUrl = [NSURL URLWithString: @"http://generericfakeapi.com/user/profile/"];

显然,如果网址末尾没有斜杠,iOS就会删除Authorization头。这个问题耗费了我两天的睡眠时间。

票数 54
EN

Stack Overflow用户

发布于 2013-09-19 13:19:21

对我来说,它看起来很好。您确定您提供了有效的令牌吗?尝试像这样捕获错误

if (error) {
    NSLog(@"error : %@", error.description);
}

我的代码运行良好:

NSURL *jsonURL = [NSURL URLWithString:[NSString stringWithFormat:@"http://....ID=%i", cellID]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:jsonURL cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:120.0];
[request setValue:@"Basic ...." forHTTPHeaderField:@"Authorization"];
NSURLResponse *response;
NSError * error  = nil;
NSData *POSTReply = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];

希望能有所帮助

票数 1
EN

Stack Overflow用户

发布于 2019-05-16 19:27:18

我也有同样的问题。在我的例子中,我把"http“改成了"https”,一切正常。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/18885587

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档