Objective-C相当于curl请求

时间:2012-07-12 11:50:09

标签: iphone objective-c ios xcode curl

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

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

我已实现以下内容,并且Domain=kCFErrorDomainCFNetwork Code=303收到数据错误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];

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

2 个答案:

答案 0 :(得分: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];

答案 1 :(得分:0)

本指南似乎可以满足您的需求: http://deusty.blogspot.co.uk/2006/11/sending-http-get-and-post-from-cocoa.html

正如一个FYI,很多类都接受initWithData,而NSData有一个方法dataWithContentsOfURL,如果你想避免自己设置NSURLConnections这可能是一个更容易的方法实现你正在寻找的东西。