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、 method を持っています。自分dataWithContentsOfURLでセットアップすることを避けたい場合は、NSURLConnectionsこれが探しているものを達成するためのより簡単な方法になる可能性があります。

于 2012-07-12T11:56:48.650 に答える