2010-04-22 75 views
0

我正在编写一个示例PHP Web服务,它正在向iPhone发送GET Http请求到Web服务器。服务器端代码返回JSON数据到iPhone,服务器端的代码如下所示:无法从iPhone应用程序获取HTTP GET请求

<?php 

function getUsers(){ 
    $con=mysql_connect("localhost","root","123456") or die(mysql_error()); 

     if(!mysql_select_db("eventsfast",$con)) 
    { 
     echo "Unable to connect to DB"; 
     exit; 
    } 

    $sql="SELECT * from users"; 
    $result=mysql_query($sql); 
    if(!$result) 
    { 
     die('Could not successfully run query Error:'.mysql_error()); 
    } 
    $data = array(); 

    while($row = mysql_fetch_assoc($result)){ 
    $data['username'][] = $row['username']; 
    $data['password'][]= $row['password']; 
    } 

    mysql_close($con); 
    //print_r(json_encode($data)); 
    //return (json_encode($data)); 
    return json_encode('success'); 
} 

getUsers(); 

?> 

它是一个简单的代码,从用户表中获取的所有数据,并将其发送到iPhone应用程序。

电话应用程序

- (void)viewDidLoad { 
    [super viewDidLoad]; 
    responseData = [[NSMutableData data] retain]; 
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://localhost:8888/GetData.php"]]; 
    [[NSURLConnection alloc] initWithRequest:request delegate:self]; 
} 

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response 
{ 
    [responseData setLength:0]; 
} 
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data 
{ 
    [responseData appendData:data]; 
} 
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error 
{ 
    label.text = [NSString stringWithFormat:@"Connection failed: %@", [error description]]; 
} 
- (void)connectionDidFinishLoading:(NSURLConnection *)connection 
{ 
    [connection release]; 

    NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding]; 

    [responseData release]; 

    NSError *error; 
    SBJSON *json = [[SBJSON new] autorelease]; 
    NSArray *luckyNumbers = [json objectWithString:responseString error:&error]; 
    [responseString release]; 

    if (luckyNumbers == nil) 
     label.text = [NSString stringWithFormat:@"JSON parsing failed: %@", [error localizedDescription]]; 
    else { 
     NSMutableString *text = [NSMutableString stringWithString:@"Lucky numbers:\n"]; 

     for (int i = 0; i < [luckyNumbers count]; i++) 
      [text appendFormat:@"%@\n", [luckyNumbers objectAtIndex:i]]; 
     NSLog(text); 

     label.text = text; 
    } 
} 

的问题

的问题是,什么是对应用程序的iPhone那边传来。该响应不包含任何内容。

+1

你能修正代码清单1.固定间距,以便代码格式正确,并且2.只包括与你的问题相关的班级部分? – 2010-04-22 07:29:00

+0

我认为你的web服务需要你还没有通过的USERID和PASSWORD。 – Tirth 2010-04-22 07:48:10

回答

0

@ user3171192, 我认为会有问题是你不通过用户ID和密码的NSURLRequest到Web service.Therefore它可能也可以不给你连接的响应。 请使用

-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data 
{ 
    [responseData appendData:data]; 
    NSLog(@"Response of web service %@", responseData); 
} 

的部分您将获得广发行代码的确切回复。 我希望你能解决你的问题。 对不起英文。