我正在尝试从iOS发送JSON。 这就是我到目前为止所做的:
+ (NSDictionary *)SendJSON:(NSString *)jsonString toAddress:(NSString *)address
{
NSData *postData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:address]];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setHTTPBody:postData];
NSURLResponse *response;
NSData *POSTReply = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
NSLog(@"%@",[NSJSONSerialization JSONObjectWithData:POSTReply options:kNilOptions error:nil] );
NSDictionary *jsonresponse = POSTReply ? [NSJSONSerialization JSONObjectWithData:POSTReply options:kNilOptions error:nil] : nil;
return jsonresponse;
}
如果我像这样发送jsonString,它可以正常工作:
NSString *jsonString = [NSString stringWithFormat:@"username=%@&password=%@", self.txtUsername.text, self.txtPassword.text];
但如果我尝试使用JSON格式发送:
@"{ \"username\" : \"%@\", \"password\" : \"%@\" }"
它不起作用 任何想法为什么?
PS:此信息正在发送到Rails服务器。
答案 0 :(得分:3)
您可能需要适当地设置Content-Type,因为您在POST正文中发送了JSON。
这应该做的,替换你的x-www-form-urlencoded:
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];