8

我试图在 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];

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

4

2 回答 2

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];
于 2012-07-12T13:13:44.103 回答
0

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

仅供参考,许多类都接受 initWithData,并且NSData有一个方法dataWithContentsOfURL,如果您想避免自己设置,NSURLConnections这可能是实现您正在寻找的更简单的方法。

于 2012-07-12T11:56:48.650 回答