gpt4 book ai didi

iphone - Objective-C 等效于 curl 请求

转载 作者:可可西里 更新时间:2023-11-01 03:08:20 24 4
gpt4 key购买 nike

我正试图在 Objective-C 中操纵这个 curl 请求:

curl -u username:password "http://www.example.com/myapi/getdata"

我已经实现了以下内容,并且我收到了一个数据获取错误 Domain=kCFErrorDomainCFNetwork Code=303 with NSErrorFailingURLKey=http://www.example.com/myapi/getdata :

// Make a call to the API to pull out the categories
NSURL *url = [NSURL URLWithString:@"http://www.example.com/myapi/getdata"];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];

// Create the username:password string for the request
NSString *loginString = [NSString stringWithFormat:@"%@:%@", API_USERNAME, API_PASSWORD];

// Create the authorisation string from the username password string
NSData *postData = [loginString dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];

[request setURL:url];
[request setHTTPMethod:@"GET"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postData];

NSError *error;
NSURLResponse *response;
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];

我希望有人能发现我在尝试操纵 curl 请求时出错的地方,并指出正确的方向。有什么明显的我错过了吗? API 返回的数据为 JSON 格式。

最佳答案

我发现最好的办法是不要尝试在代码中进行身份验证,而是直接将其放在 URL 本身中。工作代码如下所示:

NSURL *url = [NSURL URLWithString: [NSString stringWithFormat:@"http://%@:%@@www.example.com/myapi/getdata", API_USERNAME, API_PASSWORD]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

[request setURL:url];
[request setHTTPMethod:@"GET"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];

NSError *error;
NSURLResponse *response;
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];

关于iphone - Objective-C 等效于 curl 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11451205/

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