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

如何在iOS5中将JSON数据对象发布到服务器?,json,http,post,ios5,webserver,Json,Http,Post,Ios5,Webserver,我想使用JSON数据类型,使用POST方法将在iOS上创建的新对象发送到接收服务器。据我所知,在iOS中从服务器接收数据时,所有的JSON处理都被苹果通过iOS 5简化了。但与获取JSON对象不同的是,在我能找到的任何地方都没有真正描述发布这些对象 我尝试解决问题的第一步如下: //build an info object and convert to json NSDictionary *newDatasetInfo = [NSDictionary dictionaryWith

我想使用
JSON
数据类型,使用
POST
方法将在iOS上创建的新对象发送到接收服务器。据我所知,在iOS中从服务器接收数据时,所有的
JSON
处理都被苹果通过iOS 5简化了。但与获取JSON对象不同的是,在我能找到的任何地方都没有真正描述发布这些对象

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

    //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对象发送到服务器。
有人能帮我一下吗?

我试了一下,找到了答案,下面是我的代码:

    //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];
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];
-(iAction)txtFetchData2:(id)发送方{
NSString*queryString=[NSString stringWithFormat:@”http://example.com/username.php?name=%@“,[self.txtName text]];
NSMutableURLRequest*theRequest=[NSMutableURLRequest
requestWithURL:[NSURL URLWithString:
查询字符串]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
NSDictionary*jsonDictionary=[NSDictionary Dictionary WithObjectsAndKeys:
@“值1”@“键1”,
@“值2”@“键2”,
零];
n错误*错误;
NSData*jsonData=[NSJSONSerialization dataWithJSONObject:jsonDictionary
选项:nsjsonwritingprettyptederror:&error];
[TheRequestSetHttpMethod:@“POST”];
[TheRequestAddValue:@“应用程序/json”用于HttpHeaderField:@“内容类型”];
//应该在这里检查并处理错误,但我们没有
[请求集httpbody:jsonData];
[NSURLConnection sendAsynchronousRequest:theRequest队列:[NSOperationQueue mainQueue]完成处理程序:^(NSURResponse*响应,NSData*数据,NSError*错误){
如果(错误){
//做错事
}否则{
NSString*responseText=[[NSString alloc]initWithData:数据编码:NSASCIIStringEncoding];
NSLog(@“响应:%@”,响应文本);
NSString*newLineStr=@“\n”;
responseText=[responseText StringByReplacingOfString:@“
”with string:newLineStr]; [self.lbldatasettext:responseText]; } }]; }
您能否详细说明您的代码中发生了什么?我现在已经在自己的应用程序中使用了它,但我真的不知道它在做什么。我了解字典并将其转换为JSON的数据,但对我来说,URLRequest和URLConnection的所有内容都是未知的。任何澄清都很好!NSURLRequest基本上是一个用于设置web获取属性的对象。在正常的抓取中,您会自动设置最常用的默认值,但由于我想发送数据,我想使用HTTP POST方法,并因为我想接收JSON对象,所以我通过将内容类型和Accept HTTP header字段设置为JSON格式来告诉服务器这一点。要了解更多关于HTTP协议,特别是HTTP头的信息,只需搜索它们或阅读此处和此处。要了解更多关于NSURLConnection的信息,我认为最好的方法是阅读此处Apple文档中的类引用。一般来说,我只能鼓励您首先查看Apple文档,因为它是学习这些东西的一个很好的(而且绝对是最新的)来源。哦,当然我的意思是我想发送一个JSON对象,而不是接收。编辑时间已经结束了…:(@CGee For the error:&error您是否只是声明一个NSError并将其设置为nil?因为我尝试了,它只是崩溃了??
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];
- (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];
    }
}];
}