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

cURL request works, but not an equivalent NSURLSession request

这个 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 中可能做错了什么吗?

基本身份验证凭据应附加在 header。

斯威夫特3:

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

验证 Authorization header