如何在iOS5中将JSON数据对象发布到服务器?
问题描述:
我想使用JSON
数据类型将在iOS上创建的新对象发送到接收服务器,并使用POST
方法。据我所知,在iOS中接收数据从服务器,是所有的JSON
处理都被苹果公司简化了iOS 5的引入。但是与GET JSON对象相反,POST的这些并没有真正描述在任何我能找到的地方...如何在iOS5中将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对象到服务器。 有谁能帮我解决吗?
答
我的工作,这也使周围试图一点,这是我的代码:
答
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];
答
的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];
答
- (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];
}
}];
}
你能上什么是你的代码可能发生的阐述?我现在在自己的应用程序中使用过它,但我真的不知道它在做什么。我理解字典并将其转换为JSON数据,但URLRequest和URLConnection的所有内容对我而言都是未知的。任何澄清将是伟大的! – Jonathan 2013-09-04 17:37:26
NSURLRequest基本上是一个对象,用于设置Web抓取的属性。在正常的提取中,你会自动设置最常用的默认值,但是因为我想发送数据,所以我想使用HTTP POST方法,并且导致我想要接收JSON对象,所以我通过设置Content-Type并将HTTP头字段接受为JSON格式。要详细了解HTTP协议,特别是HTTP头,只需搜索它们或在这里阅读http://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol和这里http://en.wikipedia.org/wiki/List_of_HTTP_header_fields。 – CGee 2013-09-05 12:36:13
要了解有关NSURLConnection的更多信息,我认为最好的方法是在Apples文档中阅读它的类引用https://developer.apple.com/library/ios/documentation/Cocoa/Reference/Foundation/Classes/NSURLConnection_Class/Reference/的reference.html。总的来说,我只能鼓励你首先看一看Apples文档,因为它是学习这些东西的好的(绝对是最新的)源代码。 – CGee 2013-09-05 12:41:12