JSON解析,如何获得来自服务器的响应
问题描述:
我有以下细节,用于从服务器获取数据。 methodIdentifier和Web服务名称的用法是什么?JSON解析,如何获得来自服务器的响应
{"zip":"12345","methodIdentifier":"s_dealer"}
url:- http://xxxxxxxxxxxxxxx.com/api.php
method: post
web service name: s_dealer
response : {"success":"0","dealer":[info...]}
我不知道如何发送邮编号码 “12345”的URL。请指导我正确的方向。我使用以下。
-(void)IconClicked:(NSString *)zipNumber
{
NSString *post = [NSString stringWithFormat:@"&zipNumber=%@",zipNumber];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:@"%d",[postData length]];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://xxxxxxxxxxxxxxxxxxx.com/api.php"]]];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setHTTPBody:postData];
NSURLConnection *conn = [[NSURLConnection alloc]initWithRequest:request delegate:self];
if(conn)
{
NSLog(@"Connection Successful");
}
else
{
NSLog(@"Connection could not be made");
}
receivedData = [[NSMutableData alloc]init];
}
当我打印在控制台响应:不知道更多有关API \
答
“的字符串\意外结束”,我不能肯定你的需求,但似乎服务器期待包含JSON的请求。您目前正在为请求创建主体的方式是使用标准的POST变量。
您是否尝试过改变:
NSString *post = [NSString stringWithFormat:@"&zipNumber=%@",zipNumber];
到:
NSString *post = [NSString stringWithFormat:@"{\"zip\":\"%@\",\"methodIdentifier\":\"s_dealer\"}",zipNumber];
关于你提到的其他问题,我猜有这种API的一个单一的URL。服务器使用methodidentifier
来确定要运行的服务器方法。
答
你得到这个错误是因为你没有得到一个json作为响应,但是来自Apache(或其他)的错误,具有不同的结构,并且json无法解析它。尝试我的方法来启动连接,以获得成功。
声明NSURLConnection属性并将其合成。现在:
NSString *post = [NSString stringWithFormat:@"zipNumber=%@",zipNumber];
NSString *toServer = [NSString stringWithString:@"your server with the last slash character"];
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@api.php?", toServer]];
NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:NO];
NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];
NSMutableURLRequest *urlRequest = [[[NSMutableURLRequest alloc] init] autorelease];
[urlRequest setURL:url];
[urlRequest setHTTPMethod:@"POST"];
[urlRequest setValue:postLength forHTTPHeaderField:@"Content-Length"];
[urlRequest setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[urlRequest setValue:@"utf-8" forHTTPHeaderField:@"charset"];
[urlRequest setHTTPBody:postData];
[urlRequest setTimeoutInterval:30];
NSURLConnection *tmpConn = [[[NSURLConnection alloc] initWithRequest:urlRequest delegate:self] autorelease];
self.yourConnectionProperty = tmpConn;
现在您在连接代理中使用self.yourConnectionProperty。干杯!
答
嘿老兄检查我的答案同样的问题可以帮助你......你必须使用NSURLConnection的代表来获取数据