无法从IPhone应用程序获取HTTP GET请求

时间:2010-04-22 07:27:15

标签: iphone http

我正在编写一个示例PHP Web服务,它正在从iphone向Web服务器发送GET Http请求。服务器端代码将JSON数据返回给iphone,服务器端代码如下:

<?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 个答案:

答案 0 :(得分:0)

@ user3171192, 我认为有问题的是你没有将带有 NSURLRequest 的UserID和密码传递给你的网络服务。因此它可能不会给你连接的响应。 请使用

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

您将获得GDB中代码的准确响应。 我希望你能解决你的问题。 对不起英文。