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

时间:2012-07-11 14:32:54

标签: json http post ios5 webserver

我想使用POST数据类型使用JSON方法将在iOS上创建的新对象发送到接收服务器。据我所知,在iOS中接收数据来自的服务器,所有JSON处理都是由Apple简化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?

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

4 个答案:

答案 0 :(得分: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];

答案 1 :(得分: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];
    }
}];
}

答案 2 :(得分:1)

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];

答案 3 :(得分:0)

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];