您好,我正在向服务器发送一个 http post 请求,我所指的 java 代码有一个方法作为 post 请求中的设置实体。我怎样才能在 iOS 中实现这一目标。
我目前正在将要发送的 json 数据放入正文中,但收到错误
Error 500 Cannot read request parameters due Invalid parameter, expected to be a pair
但是
{
"chatMessage" : {
"reportRequest" : "Sent",
"text" : "wdfsds acd"
}
我的代码是
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"POST"];
[request setValue:[var.projectUsername base64EncodedString] forHTTPHeaderField:@"Authorization"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setHTTPShouldHandleCookies:YES];
NSMutableDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:messageText.text,@"text",@"Sent",@"reportRequest",nil];
NSDictionary *dictionary1 = [NSDictionary dictionaryWithObjectsAndKeys:dictionary,@"chatMessage", nil];
NSError *error = nil;
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:dictionary1 options:NSJSONWritingPrettyPrinted error:&error];
[request setHTTPBody:jsonData];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[connection start];
最佳答案
在您的代码中添加:- [request setValue:@"application/json"for HTTPHeaderField:@"Content-Type"];
关于发送到 http post 和设置实体时 IOS Json 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20758270/