gpt4 book ai didi

iphone - 为 Objective C 转换 CURL 命令

转载 作者:搜寻专家 更新时间:2023-10-30 19:44:46 24 4
gpt4 key购买 nike

我在为我的 Objective C 代码转换这个 curl 命令时遇到困难:

curl -u 0ef106c78146a23becba9105d1e:X -H "Accept: application/json" -H "Content-Type: application/json" https://boomboom.c27.imonggo.com/api/products.json

这是我的 Objective-C 代码:

NSError *theError = NULL;
NSURL *theURL = [NSURL URLWithString:@"https://boomboom.c2.imonggo.com/api/products.json"];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:theURL cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:10.0f];
[theRequest setValue:@"0ef106c78146a23becba9105d1e" forHTTPHeaderField:@"username"];
[theRequest setValue:@"x" forHTTPHeaderField:@"password"];
[theRequest setValue:@"application/json" forHTTPHeaderField:@"Accept:"];
[theRequest setValue:@"application/json" forHTTPHeaderField:@"Content-Type:"];


NSURLResponse *theResponse = NULL;
NSData *theResponseData = [NSURLConnection sendSynchronousRequest:theRequest returningResponse:&theResponse error:&theError];

我的问题很可能是标题字段。

最佳答案

首先,您不需要在 HTTP header 字段名称中使用冒号。

其次,您正在执行 HTTP authentication错误的。您需要连接您的用户名和密码,username:password 并对连接后的字符串数据进行 Base64 编码。使用 base64 值作为 header 字段 Authorization 的值,使用下面的代码并放入 Base 64 编码 implementation .

    // snip
NSMutableUrlRequest* theRequest = [NSMutableUrlRequest ...]
[MyClass httpAuthorizeRequest:theRequest withUsername:@"someuser" andPassword:@"mysecret"];
// snip

+ (void)httpAuthorizeRequest:(NSMutableURLRequest*)request withUsername:(NSString*)username andPassword:(NSString*)password
{
NSString* authorizationToken = [[NSString stringWithFormat:@"%@:%@", username, password] base64Representation];
[request setValue:[NSString stringWithFormat:@"Basic %@", authorizationToken] forHTTPHeaderField:@"Authorization"];
}

关于iphone - 为 Objective C 转换 CURL 命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8982707/

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