Converting a CURL command for Objective C Converting a CURL command for Objective C curl curl

Converting a CURL command for Objective C


First of all, you don't need the colon in the HTTP header field name.

Second, you're doing the HTTP authentication wrong. You need to concat your username and password, username:password and Base64 encode the concatenated string data. Use the base64 value as value for the header field Authorization, use the code below and drop in a Base 64 encoding implementation.

    // snip    NSMutableUrlRequest* theRequest = [NSMutableUrlRequest ...]    [MyClass httpAuthorizeRequest:theRequest withUsername:@"someuser" andPassword:@"mysecret"];    // snip+ (void)httpAuthorizeRequest:(NSMutableURLRequest*)request withUsername:(NSString*)username andPassword:(NSString*)password{    NSString* authorizationToken = [[NSString stringWithFormat:@"%@:%@", username, password] base64Representation];    [request setValue:[NSString stringWithFormat:@"Basic %@", authorizationToken] forHTTPHeaderField:@"Authorization"];}


You could just build cURL for iOS. Here is a Makefile to build an iOS lib.

Save that file to your home folder as 'build-cURL.sh' then open Terminal and paste:

export CURL_VERSION=7.23.0 sh ~/build-cURL.sh

Then the script should build a static library that you can add to your project. Then you will want to add the .h files and it will be ready to go.

I used lipo to create a fat-binary of the library so it will work in both the sim and the device, download it from here. Then add the curl folder to your project, and add the library. To do this click on your project in the upper left, click on your target, hit the "Build Phases" tab, drop down "Link Binary with Libraries", hit the plus icon and choose the .a file.


I would suggest to use ASIHTTPRequest for converting cUrl to Objective C code. As I have used it and it is very easy to implement, I used the authentication of NSMutableUrlRequest but it didn't worked for me. So I am posting this for someone looking answer like me.

ASIHTTPRequest *request = [[ASIHTTPRequest alloc] initWithURL:[NSURL URLWithString:@"https://acebonita.c2.imonggo.com/api/products.json"]];[request setUsername:@"0efd245bfbf6bba4106c78146a23becba9105d1e"];[request setPassword:@"x"];[request addRequestHeader:@"Content-Type" value:@"application/json"];[request addRequestHeader:@"Accept" value:@"application/json"];[request startSynchronous]; if([request error]){    NSLog(@"Code : %d, Error: %@",[[request error] code],[[request error] description]);}NSLog(@"Code: %d, Description: %@, Message: %@",[request responseStatusCode],[request responseData],[request responseStatusMessage]);