Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
484 views
in Technique[技术] by (71.8m points)

iphone - Objective-C equivalent of curl request

I'm trying to manipulate this curl request in Objective-C:

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

I've implemented the following and I'm getting a data get error Domain=kCFErrorDomainCFNetwork Code=303 with 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];

I was hoping that someone could spot where I am going wrong with my attempt to manipulate the curl request and point me in the correct direction. Is there something obvious I'm missing out? The data returned from the API is in a JSON format.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I found that the best thing to do was to not attempt the authentication within the code and to put it straight in the URL itself. The working code looks as follows:

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];

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...