JSON解析,如何从服务器获取响应

时间:2012-07-10 13:13:51

标签: iphone ios json parsing

我有以下详细信息,用于从服务器获取数据。 methodIdentifier和Web服务名称有什么用?

{"zip":"12345","methodIdentifier":"s_dealer"}

url:- http://xxxxxxxxxxxxxxx.com/api.php
method: post
web service name: s_dealer

response : {"success":"0","dealer":[info...]}

我不知道如何使用网址发送 zip编号“12345”。请指导我正确的方向。我使用以下内容。

-(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];


}

当我在控制台中打印响应时:\“字符串的意外结束”

3 个答案:

答案 0 :(得分:0)

在不了解API的情况下,我无法确定您的要求,但似乎服务器期望请求包含JSON。您当前为请求创建正文的方式是使用标准POST变量。

您是否尝试过更改:

NSString *post = [NSString stringWithFormat:@"&zipNumber=%@",zipNumber];

为:

NSString *post = [NSString stringWithFormat:@"{\"zip\":\"%@\",\"methodIdentifier\":\"s_dealer\"}",zipNumber];

关于您的其他问题,我猜测该API只有一个网址。服务器使用methodidentifier来确定要运行的服务器方法。

答案 1 :(得分:0)

你得到这个错误,因为你没有得到一个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。干杯!

答案 2 :(得分:0)

嘿兄弟检查我的答案同样的问题可能对你有帮助...你必须使用NSURLConnection代表来获取数据

Could not make Json Request body from Iphone