Objective-C等价于curl请求

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

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

我已经实现了以下,我得到一个数据获取错误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]; 

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

我发现最好的做法是不要在代码中尝试authentication,并把它直接放在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]; 

本指南似乎做你正在寻找: http : //deusty.blogspot.co.uk/2006/11/sending-http-get-and-post-from-cocoa.html

就像一个参考,很多类接受initWithData, NSData有一个方法dataWithContentsOfURL ,如果你想避免自己设置NSURLConnections这可能是一个更容易的方法来实现你在找什么。