Objective-C相当于curl请求

Llo*_*ell 8 iphone xcode curl objective-c ios

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

curl -u username:password "http://www.example.com/myapi/getdata"
Run Code Online (Sandbox Code Playgroud)

我已经实现了以下内容,我得到一个数据出现错误Domain=kCFErrorDomainCFNetwork Code=303NSErrorFailingURLKey=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];
Run Code Online (Sandbox Code Playgroud)

我希望有人可以在我试图操纵卷曲请求并指出我正确的方向时发现我出错的地方.有什么明显的东西我错过了吗?从API返回的数据采用JSON格式.

Llo*_*ell 11

我发现最好的办法是不要在代码中尝试身份验证,并将其直接放在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];
Run Code Online (Sandbox Code Playgroud)