cURL请求有效,但不是等效的NSURLSession请求

时间:2017-07-25 03:28:49

标签: ios objective-c nsurlsession nsurlrequest

这个cURL在控制台上给我一个好结果:

curl -H "Accept: application/json" https://myusername:mypassword@somehost.com/someroute

但是这个iOS代码生成了404

NSURL *URL = [NSURL urlWithString:@"https://myusername:mypassword@somehost.com/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请求。鉴于cURL工作正常,有人可以建议我在iOS中做错了吗?

1 个答案:

答案 0 :(得分: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"];

或者,您也可以使用Authorization

验证curl -H "Accept: application/json" -H "authorization: <value>" https://somehost.com/someroute标题