1

我试图四处搜索,但找不到确切的答案。

我的朋友使用 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。)

有人可以帮忙吗?

4

1 回答 1

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.
于 2013-03-15T16:02:05.353 回答