[英]JSON parsing, How to get response from server
我有以下详细信息,用于从服务器获取数据。 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...]}
我不知道如何通过url发送邮政编码“ 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];
}
当我在控制台中打印响应时:\\“意外的字符串结尾\\”
在不了解有关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代表来获取数据
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.