【问题标题】:How do I POST JSON data object to server in iOS5?如何在 iOS5 中将 JSON 数据对象发布到服务器?
【发布时间】:2012-07-11 14:32:53
【问题描述】:

我想通过POST 方法使用JSON 数据类型将在iOS 上创建的新对象发送到接收服务器。据我所知,在 iOS 中服务器接收数据,所有JSON 处理都被 Apple 简化了,引入了 iOS 5。但与 GETting JSON 对象不同,POST 那些不是t真的描述了我能找到的任何地方......

我尝试解决问题的第一步如下所示:

    //build an info object and convert to json
    NSDictionary *newDatasetInfo = [NSDictionary dictionaryWithObjectsAndKeys:name, @"name", language, @"language", nil];

    //convert object to data
    NSData* jsonData = [NSJSONSerialization dataWithJSONObject:newDatasetInfo options:kNilOptions error:&error];

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    [request setURL:someURLSetBefore];
    [request setHTTPMethod:@"POST"];
    // any other things to set in request? or working this way?

    [[NSURLConnection alloc] initWithRequest:request delegate:self];
    // What to do with NSURLConnection? Or how to send differently?

但我真的不知道如何使用 POST 方法将 JSON 对象发送到服务器。 有人可以帮帮我吗?

【问题讨论】:

    标签: json http post ios5 webserver


    【解决方案1】:

    我尝试了一下,这是我的代码:

        //build an info object and convert to json
        NSDictionary *newDatasetInfo = [NSDictionary dictionaryWithObjectsAndKeys:name, @"name", language, @"language", nil];
    
        //convert object to data
        NSData* jsonData = [NSJSONSerialization dataWithJSONObject:newDatasetInfo options:kNilOptions error:&error];
    
        NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
        [request setURL:someURLSetBefore];
        [request setHTTPMethod:@"POST"];
        [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
        [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
        [request setHTTPBody:jsonData];
    
        // print json:
        NSLog(@"JSON summary: %@", [[NSString alloc] initWithData:jsonData
                                                         encoding:NSUTF8StringEncoding]);
        NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
        [connection start];
    

    【讨论】:

    • 您能否详细说明您的代码中发生了什么?我现在已经在我自己的应用程序中使用了它,但老实说,我不太了解它在做什么。我了解字典并将其转换为 JSON 的数据,但 URLRequest 和 URLConnection 的所有内容对我来说都是未知的。任何澄清都会很棒!
    • 一个 NSURLRequest 基本上是一个对象来设置你的网络获取的属性。在正常提取中,您将自动设置最常用的默认值,但由于我想发送数据,我想使用 HTTP POST 方法并因为我想接收 JSON 对象,我通过设置 Content-Type 告诉服务器这一点并接受 JSON 格式的 HTTP 标头字段。要了解有关 HTTP 协议,尤其是 HTTP 标头的更多信息,只需搜索它们或阅读此处en.wikipedia.org/wiki/Hypertext_Transfer_Protocol 和此处en.wikipedia.org/wiki/List_of_HTTP_header_fields
    • 要了解有关 NSURLConnection 的更多信息,我认为最好的方法是在此处的 Apple 文档中阅读其类参考 developer.apple.com/library/ios/documentation/Cocoa/Reference/…。一般来说,我只能鼓励你先看看 Apple 的文档,因为它是学习这些东西的绝佳(而且绝对是最新的)资源。
    • 哦,当然我的意思是我想发送一个 JSON 对象,而不是接收。编辑时间已经结束了... :(
    • @CGee 对于错误:&错误,您是否只是声明一个 NSError 并将其设置为上面的 nil ?因为我试过了,它只是崩溃了??
    【解决方案2】:
    - (IBAction)txtFetchData2:(id)sender {
    NSString *queryString = [NSString stringWithFormat:@"http://example.com/username.php?name=%@", [self.txtName text]];
    NSMutableURLRequest *theRequest=[NSMutableURLRequest
                              requestWithURL:[NSURL URLWithString:
                                              queryString]
                              cachePolicy:NSURLRequestUseProtocolCachePolicy
                              timeoutInterval:60.0];
    NSDictionary* jsonDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
                                    @"Value1", @"Key1",
                                    @"Value2", @"Key2",
                                    nil];
    NSError *error;
    NSData* jsonData = [NSJSONSerialization dataWithJSONObject:jsonDictionary
                           options:NSJSONWritingPrettyPrinted error:&error];
    [theRequest setHTTPMethod:@"POST"];
    [theRequest addValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    // should check for and handle errors here but we aren't
    [theRequest setHTTPBody:jsonData];
    [NSURLConnection sendAsynchronousRequest:theRequest queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
        if (error) {
            //do something with error
        } else {
            NSString *responseText = [[NSString alloc] initWithData:data encoding: NSASCIIStringEncoding];
            NSLog(@"Response: %@", responseText);
    
            NSString *newLineStr = @"\n";
            responseText = [responseText stringByReplacingOccurrencesOfString:@"<br />" withString:newLineStr];            
            [self.lblData setText:responseText];
        }
    }];
    }
    

    【讨论】:

      【解决方案3】:

      NSString *strUrl = @"URL"; NSURL *url = [NSURL URLWithString:strUrl];

      NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60.0];
      
      // For set postdata in string
      NSString *strPatientID = [NSString stringWithFormat:@"%@%@%@%@",self.txtDegit1.text,self.txtDegit2.text,self.txtDegit3.text,self.txtDegit4.text];
      NSString *deviceToken = @"";
      postString = [NSString stringWithFormat:@"practiceid=%@&email=%@&password=%@&devicetoken=%@",strPatientID,self.txtUsername.text,self.txtPassword.text,deviceToken];
      
      
      NSMutableData *httpDataBody = [NSMutableData data];
      [httpDataBody appendData:[postString dataUsingEncoding:NSUTF8StringEncoding]];
      
      NSString *strPostLength = [NSString stringWithFormat:@"%lu",[httpDataBody length]];
      
      if ([httpDataBody length ] > 0){
      
          [request addValue:@"application/x-www-form-urlencoded charset=utf-8" forHTTPHeaderField:@"Content-Type"];
          [request setHTTPMethod:@"POST"];
          [request addValue:strPostLength forHTTPHeaderField:@"Content-Type"];
          [request setHTTPBody:httpDataBody];
      
      }
      
      urlConnection = [[NSURLConnection alloc]initWithRequest:request delegate:self];
      [urlConnection start];
      

      【讨论】:

        【解决方案4】:
        NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
            [request setURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://webstar52.com/demo/webcommunity/work.php"]]];
            NSString *post = [NSString stringWithFormat:@"&tag=%@&user_id=%@",@"getcontact",@"10408"]; 
            NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
            NSString *postLength = [NSString stringWithFormat:@"%d",[postData length]];
            [request setHTTPMethod:@"POST"];      
            [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
            [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Current-Type"];
            [request setHTTPBody:postData];
          conn  = [[NSURLConnection alloc]initWithRequest:request delegate:self];
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2013-06-08
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多