如何在iOS5中将JSON数据对象发布到服务器?

CGe*_*Gee 7 post webserver json http ios5

我想POST使用JSON数据类型的方法将在iOS上创建的新对象发送到接收服务器.根据我对 iOS服务器接收数据的了解JSON,苹果公司通过iOS 5的引入简化了所有处理.但与GETting JSON对象相比,POST这些并不是我能找到的任何地方.

我尝试解决问题的第一步看起来如下:

    //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?
Run Code Online (Sandbox Code Playgroud)

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

CGe*_*Gee 16

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

    //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];
Run Code Online (Sandbox Code Playgroud)