2012-07-10 111 views
0

我有以下細節,用於從服務器獲取數據。 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 \

回答

0

「的字符串\意外結束」,我不能肯定你的需求,但似乎服務器期待包含JSON的請求。您目前正在爲請求創建主體的方式是使用標準的POST變量。

您是否嘗試過改變:

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

到:

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

關於你提到的其他問題,我猜有這種API的一個單一的URL。服務器使用methodidentifier來確定要運行的服務器方法。

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。乾杯!