【发布时间】:2011-08-31 02:14:48
【问题描述】:
您好,我需要帮助来建立与 Web 服务的 HTTP POST 连接。我完全不知道该怎么做。
我只在制作 NSURLConnection 方面有过经验,我将所需的输入参数作为 URL 的一部分传递。现在似乎不同了,因为我只提供了一个网站和请求 JSON 正文。
{
"lastmodified":"String content",
"passengerId":9223372036854775807,
"password":"String content",
"userId":"String content"
}
有人能解释一下吗?假设网站是 www.myURL/operations/AddItem.com
编辑 - 我在这里做错了什么?
NSError *theError = nil;
NSArray *keys = [NSArray arrayWithObjects:@"userId", @"password", nil];
NSArray *objects = [NSArray arrayWithObjects:userNameTextField.text, passwordTextField.text, nil];
NSDictionary *jsonDictionary = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
NSString *myJSONString =[jsonDictionary JSONRepresentation];
NSData *myJSONData =[myJSONString dataUsingEncoding:NSUTF8StringEncoding];
NSLog(@"myJSONString :%@", myJSONString);
NSLog(@"myJSONData :%@", myJSONData);
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"http://153.20.32.74/11AprP306/passenger/item"]];
[request setHTTPBody:myJSONData];
[request setHTTPMethod:@"POST"];
NSURLResponse *theResponse =[[NSURLResponse alloc]init];
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&theResponse error:&theError];
NSLog(@"response : %@", theResponse);
NSLog(@"error : %@", theError);
NSLog(@"data : %@", data);
NSMutableString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"string: %@", string);
NSDictionary *jsonDictionaryResponse = [string JSONValue];
NSLog(@"dic: %@", jsonDictionaryResponse);
[string release];
[theResponse release];
我正在阅读string: <?xml version="1.0" encoding="utf-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1 transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Request Error</title>
<style>BODY {..... 'The incoming message has an unexpected message format 'Raw'. The expected message formats for the operation are 'Xml', 'Json'.
是因为我没有传递一些值(lastmodified 和passengerId)吗?我不知道他们为什么需要这两个参数,因为这个请求只是创建一个新帐户。
【问题讨论】:
-
ASIHTTPRequest。使用appendPostData:或appendPostDataFromFile:方法添加JSON dict。