2017-07-25 83 views
0

这卷曲给了我一个很好的结果在控制台上:卷曲的要求工作,但不等同NSURLSession请求

curl -H "Accept: application/json" https://myusername:[email protected]/someroute 

但这iOS的代码生成404

NSURL *URL = [NSURL urlWithString:@"https://myusername:[email protected]/someroute"]; 
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL]; 
request.HTTPMethod = @"GET"; 
[request addValue:@"application/json" forHTTPHeaderField:@"Accept"]; 

NSURLSession *session = [NSURLSession sharedSession]; 
[[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { 
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO; 
    // here, data is nil, there's no error, but the api returns 404 
}] resume]; 

我知道运输安全iOS中的设置,但我认为这些仅适用于http请求。有人可以建议我可能做错了在iOS中考虑到cURL工作正常吗?

回答

3

基本认证凭证应附加在标题中。

Swift3:

let raw = "myusername:mypassword" 
let encoded = raw.data(using: String.Encoding.ascii)! 
let value = "Basic \(encoded.base64EncodedString())" 

ObjC(未测试)

NSString *raw = @"myusername:mypassword"; 
NSData *encoded = [raw dataUsingEncoding:NSASCIIStringEncoding]; 
NSString *value = [NSString stringWithFormat:@"Basic %@", [encoded base64EncodedStringWithOptions:0]]; 
[request setValue:value forHTTPHeaderField:@"Authorization"]; 

另外,您还可以验证使用curl -H "Accept: application/json" -H "authorization: <value>" https://somehost.com/someroute

+0

完全Authorization报头。作为附加信息:我认为cURL在内部基本上就是这样做的。您可以将用户名和密码这样写入URL中,这只是为了方便。至少你不会从cURL接受的同一个字符串中获得有效的NSURLRequest。 – Gero

+0

我知道你不应该在这个网站上说'谢谢你',但是谢谢你。 – user1272965