我有一个NSData对象,代表由IOS Facebook SDK提供的Facebook用户。此对象是JSON格式的,我试图将其发布到服务器应用程序。下面是我执行HTTP Post的Objective C代码。此代码的问题是服务器上的请求正文是空的。有人能发现我做错了吗?
-(void)postUserDataToServer:(NSString *) user {
// Convert the JSON string to Data to be sent.
NSMutableURLRequest* request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:@"http://ec2-whatever.compute-1.amazonaws.com:3000/user"]];
[request setHTTPMethod:@"POST"];
[request setValue:[NSString stringWithFormat:@"%d", [user length]] forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:user];
[NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
}
答案 0 :(得分:3)
嗯......用户不是NSData!你必须将字符串转换为数据
assert(user.length);
id bodyData = [user dataUsingEncoding:NSUTF8StringEncoding];
request.HTTPBody = bodyData;