我试图通过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所做的吗?
任何帮助都将不胜感激。
发布于 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头。这个问题耗费了我两天的睡眠时间。
发布于 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];
希望能有所帮助
发布于 2019-05-16 19:27:18
我也有同样的问题。在我的例子中,我把"http“改成了"https”,一切正常。
https://stackoverflow.com/questions/18885587
复制相似问题