80

我是 Objective-c 的新手,最近我开始在请求/响应上投入大量精力。我有一个可以调用 url(通过 http GET)并解析返回的 json 的工作示例。

工作示例如下

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    [responseData setLength:0];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    [responseData appendData:data];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
  NSLog([NSString stringWithFormat:@"Connection failed: %@", [error description]]);
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    [connection release];
  //do something with the json that comes back ... (the fun part)
}

- (void)viewDidLoad
{
  [self searchForStuff:@"iPhone"];
}

-(void)searchForStuff:(NSString *)text
{
  responseData = [[NSMutableData data] retain];
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.whatever.com/json"]];
    [[NSURLConnection alloc] initWithRequest:request delegate:self];
}

我的第一个问题是——这种方法会扩大规模吗?或者这不是异步的(意味着我在应用程序等待响应时阻塞了 UI 线程)

我的第二个问题是 - 我如何修改请求部分以执行 POST 而不是 GET?只是像这样修改HttpMethod吗?

[request setHTTPMethod:@"POST"];

最后 - 我如何将一组 json 数据作为一个简单的字符串添加到这篇文章中(例如)

{
    "magic":{
               "real":true
            },
    "options":{
               "happy":true,
                "joy":true,
                "joy2":true
              },
    "key":"123"
}

先感谢您

4

8 回答 8

105

这是我所做的(请注意,转到我的服务器的 JSON 需要是一个字典,其中 key = question..ie {:question => { dictionary } } 具有一个值(另一个字典):

NSArray *objects = [NSArray arrayWithObjects:[[NSUserDefaults standardUserDefaults]valueForKey:@"StoreNickName"],
  [[UIDevice currentDevice] uniqueIdentifier], [dict objectForKey:@"user_question"],     nil];
NSArray *keys = [NSArray arrayWithObjects:@"nick_name", @"UDID", @"user_question", nil];
NSDictionary *questionDict = [NSDictionary dictionaryWithObjects:objects forKeys:keys];

NSDictionary *jsonDict = [NSDictionary dictionaryWithObject:questionDict forKey:@"question"];

NSString *jsonRequest = [jsonDict JSONRepresentation];

NSLog(@"jsonRequest is %@", jsonRequest);

NSURL *url = [NSURL URLWithString:@"https://xxxxxxx.com/questions"];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
             cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];


NSData *requestData = [jsonRequest dataUsingEncoding:NSUTF8StringEncoding];

[request setHTTPMethod:@"POST"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:[NSString stringWithFormat:@"%d", [requestData length]] forHTTPHeaderField:@"Content-Length"];
[request setHTTPBody: requestData];

NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];
if (connection) {
 receivedData = [[NSMutableData data] retain];
}

然后接收到的数据由以下方式处理:

NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSDictionary *jsonDict = [jsonString JSONValue];
NSDictionary *question = [jsonDict objectForKey:@"question"];

这不是 100% 清楚的,需要重新阅读,但一切都应该在这里让你开始。据我所知,这是异步的。进行这些调用时,我的 UI 未锁定。希望有帮助。

于 2010-12-17T01:11:38.830 回答
7

我为此挣扎了一段时间。在服务器上运行 PHP。此代码将发布一个 json 并从服务器获取 json 回复

NSURL *url = [NSURL URLWithString:@"http://example.co/index.php"];
NSMutableURLRequest *rq = [NSMutableURLRequest requestWithURL:url];
[rq setHTTPMethod:@"POST"];
NSString *post = [NSString stringWithFormat:@"command1=c1&command2=c2"];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding];
[rq setHTTPBody:postData];
[rq setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];

[NSURLConnection sendAsynchronousRequest:rq queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
 {
     if ([data length] > 0 && error == nil){
         NSError *parseError = nil;
         NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:&parseError];
         NSLog(@"Server Response (we want to see a 200 return code) %@",response);
         NSLog(@"dictionary %@",dictionary);
     }
     else if ([data length] == 0 && error == nil){
         NSLog(@"no data returned");
         //no data, but tried
     }
     else if (error != nil)
     {
         NSLog(@"there was a download error");
         //couldn't download

     }
 }];
于 2015-02-11T15:03:26.067 回答
6

我建议使用ASIHTTPRequest

ASIHTTPRequest 是一个易于使用的 CFNetwork API 包装器,它使与 Web 服务器通信的一些更繁琐的方面变得更容易。它是用 Objective-C 编写的,适用于 Mac OS X 和 iPhone 应用程序。

它适合执行基本的 HTTP 请求并与基于 REST 的服务(GET / POST / PUT / DELETE)交互。包含的 ASIFormDataRequest 子类使得使用 multipart/form-data 提交 POST 数据和文件变得容易。


请注意,原作者停止了这个项目。有关原因和替代方法,请参阅以下帖子:http: //allseeing-i.com/%5Brequest_release%5D

我个人是AFNetworking的忠实粉丝

于 2010-12-16T02:33:55.710 回答
3

你们中的大多数人现在已经知道这一点,但我发布了这个,以防万一,你们中的一些人仍在为 iOS6+ 中的 JSON 苦苦挣扎。

在 iOS6 和更高版本中,我们有NSJSONSerialization 类,它速度很快,并且不依赖于包含“外部”库。

NSDictionary *result = [NSJSONSerialization JSONObjectWithData:[resultStr dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil]; 

这是 iOS6 和更高版本现在可以有效解析 JSON 的方式。SBJson 的使用也是 ARC 之前的实现,如果您在 ARC 环境中工作,也会带来这些问题。

我希望这有帮助!

于 2013-11-12T14:49:47.460 回答
2

这是一篇使用Restkit的好文章

它解释了将嵌套数据序列化为 JSON 并将数据附加到 HTTP POST 请求。

于 2013-08-19T16:34:57.760 回答
2

由于我对 Mike G 对代码现代化的回答的编辑被 3 比 2 拒绝为

此编辑旨在解决帖子的作者,作为编辑毫无意义。它应该写成评论或答案

我在这里将我的编辑作为单独的答案重新发布。正如 Rob 的 15 票赞成评论所暗示的那样,此编辑删除了JSONRepresentation依赖关系。NSJSONSerialization

    NSArray *objects = [NSArray arrayWithObjects:[[NSUserDefaults standardUserDefaults]valueForKey:@"StoreNickName"],
      [[UIDevice currentDevice] uniqueIdentifier], [dict objectForKey:@"user_question"],     nil];
    NSArray *keys = [NSArray arrayWithObjects:@"nick_name", @"UDID", @"user_question", nil];
    NSDictionary *questionDict = [NSDictionary dictionaryWithObjects:objects forKeys:keys];

    NSDictionary *jsonDict = [NSDictionary dictionaryWithObject:questionDict forKey:@"question"];

    NSLog(@"jsonRequest is %@", jsonRequest);

    NSURL *url = [NSURL URLWithString:@"https://xxxxxxx.com/questions"];

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
                 cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];


    NSData *requestData = [NSJSONSerialization dataWithJSONObject:dict options:0 error:nil]; //TODO handle error

    [request setHTTPMethod:@"POST"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [request setValue:[NSString stringWithFormat:@"%d", [requestData length]] forHTTPHeaderField:@"Content-Length"];
    [request setHTTPBody: requestData];

    NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];
    if (connection) {
     receivedData = [[NSMutableData data] retain];
    }

然后接收到的数据由以下方式处理:

NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
    NSDictionary *question = [jsonDict objectForKey:@"question"];
于 2015-11-03T17:54:46.447 回答
0

这是一个使用 NSURLConnection +sendAsynchronousRequest: (10.7+, iOS 5+) 的更新示例,“发布”请求与接受的答案相同,为清楚起见,此处省略:

NSURL *apiURL = [NSURL URLWithString:
    [NSString stringWithFormat:@"http://www.myserver.com/api/api.php?request=%@", @"someRequest"]];
NSURLRequest *request = [NSURLRequest requestWithURL:apiURL]; // this is using GET, for POST examples see the other answers here on this page
[NSURLConnection sendAsynchronousRequest:request
                                   queue:[NSOperationQueue mainQueue]
                       completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
     if(data.length) {
         NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
         if(responseString && responseString.length) {
             NSLog(@"%@", responseString);
         }
     }
}];
于 2013-12-09T14:42:42.597 回答
0

您可以尝试使用此代码发送 json 字符串

NSData *jsonData = [NSJSONSerialization dataWithJSONObject:ARRAY_CONTAIN_JSON_STRING options:NSJSONWritin*emphasized text*gPrettyPrinted error:NULL];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSString *WS_test = [NSString stringWithFormat:@"www.test.com?xyz.php&param=%@",jsonString];
于 2016-10-04T12:28:52.567 回答