我试图四处搜索,但找不到确切的答案。
我的朋友通过使用cURL实现网站以JSON格式返回数据
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"
我尝试编写代码以使我的iOS应用程序检索数据。但我不能。我总是得到错误,数据甚至无法通过NSURLConnection加载。 这是我的代码:
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];
根本没有数据。我收到此错误消息:
无法完成操作。 (kCFErrorDomainCFNetwork错误303.)
有人可以帮忙吗?
答案 0 :(得分:3)
这是因为您在GET
请求中传递了一个正文。您想要POST
请求。
来自curl
联机帮助页:
-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.