【发布时间】: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 地址。每个人都可以收听该消息并提取用户名和密码。
-
亲爱的请参考这个链接..stackoverflow.com/questions/19807368/…
-
我建议您创建 NSError 对象并放入创建 json 对象的方法。如果您从该操作中得到 nil,则检查错误并了解原因。
-
通读你的代码,这真是充满了错误......我提出一个建议。你修复了第一个错误(“post”将包含危险的废话,具体取决于 userNameField.text 和 passwordField.text 中包含的内容),然后我会告诉你下一个错误。
标签: ios objective-c json xcode