使用 Objective C 创建 JSON 数据并将其发送到服务器
Posted
技术标签:
【中文标题】使用 Objective C 创建 JSON 数据并将其发送到服务器【英文标题】:Create and send JSON data to server using Objective C 【发布时间】:2015-09-24 09:39:04 【问题描述】:我正在尝试使用 POST 方法将 JSON 数据发送到服务器端,但我的代码给出了 null JSON 值。我正在使用 Objective C,我从 textField 获取数据并将其转换为字符串,但之后在将此值转换为 JSON 对象时,它给出了 null 值。不知道该怎么办。
这是我的代码:
- (IBAction)loginAction:(UIButton *)sender
NSString *post = [NSString stringWithFormat:@"Username=%@&Password=%@" ,self.userNameField.text,self.passwordField.text];
NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding];
postData = [postData subdataWithRange:NSMakeRange(0, [postData length] - 1)];
NSData*jsonData = [NSJSONSerialization JSONObjectWithData:postData options:NSJSONReadingMutableContainers error:nil];
NSString *postLength = [NSString stringWithFormat:@"%d",[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]init];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://172.31.144.227:8080/Analytics/rest/login/post"]]];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length" ];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Current-Type"];
[request setHTTPBody:jsonData];
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[theConnection start];
NSError *error = [[NSError alloc] init];
NSHTTPURLResponse *response = nil;
[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
【问题讨论】:
您发送的数据不是 json 格式。你似乎对此很陌生。请参考 json.org 恭喜。您在第一行代码中实现了代码注入,这是一个严重的漏洞。其次,您将用户名和密码发布到 http 地址。每个人都可以收听该消息并提取用户名和密码。 亲爱的请参考这个链接..***.com/questions/19807368/… 我建议您创建 NSError 对象并放入创建 json 对象的方法。如果您从该操作中得到 nil,则检查错误并了解原因。 通读你的代码,这真是充满了错误......我提出一个建议。你修复了第一个错误(“post”将包含危险的废话,具体取决于 userNameField.text 和 passwordField.text 中包含的内容),然后我会告诉你下一个错误。 【参考方案1】:-(void)MessagePost
NSString * post =[NSString stringWithFormat:@"http://url.com/clients/project_id=%@&user_id=58&question=%@&send_enquiry=Send",[[self.recordchat objectForKey:@"id"] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],[[_txtfield text] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSLog(@"%@",post);
NSData *postdata= [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength=[NSString stringWithFormat:@"%lu",(unsigned long)[postdata length]];
NSMutableURLRequest *request= [[NSMutableURLRequest alloc]init];
[request setURL:[NSURL URLWithString:post]];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postdata];
NSError *error;
NSURLResponse *response;
postdata=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *returnstring=[[NSString alloc]initWithData:postdata encoding:NSUTF8StringEncoding];
NSLog(@"String : %@",returnstring);
if (postdata)
NSDictionary *dict= [NSJSONSerialization JSONObjectWithData:postdata options:NSJSONReadingMutableContainers error:nil];
NSDictionary* latestLoans = [dict objectForKey:@"status"];
NSLog(@"Status dict = %@",latestLoans);
else NSLog(@"Error while posting messages.");
【讨论】:
谢谢@Dilip Tiwari。非常感谢您的帮助。【参考方案2】:instead of writing NSString *post = [NSString stringWithFormat:@"Username=%@&Password=%@" ,self.userNameField.text,self.passwordField.text];
you should use this
NSMutableDictionary *post = [[NSMutableDictionary alloc]init];
[post setValue:self.userNameField.text forKey:@"Username"];
[post setValue:self.passwordField.text forKey:@"Password"];
【讨论】:
嗨 Indrajit...感谢您的建议...如果我在程序中遇到任何问题,我一定会告诉您...再次感谢... :- )【参考方案3】:试试这个 -
- (IBAction)loginAction:(UIButton *)sender
NSDictionary *dictDetails = @
@"Username" : self.userNameField.text,
@"Password" : self.passwordField.text
;
NSString *jsonRequest = [dict JSONRepresentation];
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://172.31.144.227:8080/Analytics/rest/login/post"]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
NSData *requestData = [NSData dataWithBytes:[jsonRequest UTF8String] length:[jsonRequest length]];
[request setHTTPMethod:@"POST"];
[request setHTTPBody: requestData];
[request setValue:[NSString stringWithFormat:@"%lu", (unsigned long)
[requestData length]] forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Current-Type"];
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[theConnection start];
NSError *error = [[NSError alloc] init];
NSHTTPURLResponse *response = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
【讨论】:
嗨 nilam,在使用您的代码后..它显示“No visible @interface for "NSMutableDictionary" 声明选择器 "JSONRepresentation".. 请您帮帮我.. 期待您的回复..谢谢.. :-)【参考方案4】:最后我写了正确的代码,现在可以正常工作了。如果需要进一步修改,请建议我.. 谢谢大家的时间和支持。。 这是我的代码:
- (IBAction)loginAction:(UIButton *)sender
NSMutableDictionary *post = [[NSMutableDictionary alloc]init];
[post setValue:self.userNameField.text forKey:@"username"];
[post setValue:self.passwordField.text forKey:@"password"];
NSArray* notifications = [NSArray arrayWithObjects:post, nil];
NSError *writeError = nil;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:notifications options:kNilOptions error:&writeError];
NSString *postLength = [NSString stringWithFormat:@"%d",[jsonData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]init];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://172.31.144.227:8080/Analytics/rest/login"]]];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length" ];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:jsonData];
NSLog(@"JSON Summary: %@", [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]);
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[theConnection start];
NSError *error = [[NSError alloc] init];
NSHTTPURLResponse *response = nil;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSLog(@"Response Error= %@", response);
if ([response statusCode] >=200 && [response statusCode] <300)
NSData *responseData = [[NSData alloc]initWithData:urlData];
NSMutableDictionary *jsonObject = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error:nil];
NSLog(@"Random Output= %@", jsonObject);
[self performSegueWithIdentifier:@"DASHBOARDSEGUE" sender:sender];
else
[self alertStatus:@"Connection Failed" :@"Login Failed!"];
【讨论】:
以上是关于使用 Objective C 创建 JSON 数据并将其发送到服务器的主要内容,如果未能解决你的问题,请参考以下文章
如何在 Objective c 中使用 JSON 服务发布数据