Kong Hantrakool
Kong Hantrakool

Reputation: 1865

Objective C equivalent of cURL to work with JSON

I tried to search around but can't find the exact answer.

My friend implements the website to return data in JSON by using cURL as below

curl http://example.com//api/v1/opens_set_current_position -d '{"latitude":"53.041", "longitude":"-2.90545", "radius":"100000"}' -X GET -H "Content-type: application/json"

I tried to write code to make my iOS app to retrieve data. But I can't. I always get error the data can't even load via NSURLConnection. Here is my code:

NSString *requestString = [NSString stringWithFormat:
                         @"http://example.com//api/v1/opens_set_current_position"];

NSURL *url = [NSURL URLWithString:requestString];

NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
[req setHTTPMethod:@"GET"];

[req addValue:@"application/json" forHTTPHeaderField:@"Content-type"];

NSString *dataString = @"{\"latitude\":\"53.041\", \"longitude\":\"-2.90545\", \"radius\":\"100000\"}";

NSData *requestData = [NSData dataWithBytes:[dataString UTF8String] length:[dataString length]];

[req setHTTPBody:requestData];

NSURLResponse *theResponse = NULL;
NSError *theError = NULL;
NSData *theResponseData = [NSURLConnection sendSynchronousRequest:req returningResponse:&theResponse error:&theError];

The data didn't come at all. I get this error message:

The operation couldn’t be completed. (kCFErrorDomainCFNetwork error 303.)

Can somebody help?

Upvotes: 1

Views: 943

Answers (1)

trojanfoe
trojanfoe

Reputation: 122391

This is because you are passing a body in a GET request. You want a POST request instead.

From the curl manpage:

-d/--data <data>
(HTTP)  Sends  the  specified data in a POST request to the HTTP server,
in the same way that a browser does when a user has filled in an HTML form
and presses the submit button. This will cause curl to pass the data to the
server using the content-type application/x-www-form-urlencoded.

Upvotes: 3

Related Questions