gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 19:30:36 25 4
gpt4 key购买 nike

这个 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 中。

swift 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"];

或者,您也可以验证 Authorization header 使用 curl -H "Accept: application/json" -H "authorization: <value>" https://somehost.com/someroute

关于ios - cURL 请求有效,但不是等效的 NSURLSession 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45293412/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com