1

以下是将 NSmutable Array 发送到 PHP webservice 的 iOS 代码:

 // Getting Server Address
            AppDelegate *appDelegate =
            [[UIApplication sharedApplication] delegate];

            NSString *serverAddress = [appDelegate getServerAddress];

            serverAddress = [serverAddress stringByAppendingString:@"ABC.php"];


            NSLog(@"Server Address: %@",serverAddress);

            NSData *post = [NSJSONSerialization dataWithJSONObject:UsersArray options:NSJSONWritingPrettyPrinted error:nil];
            NSString *postLength = [NSString stringWithFormat:@"%d", [post length]];
            NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:serverAddress]];

            [request setHTTPMethod:@"POST"];
            [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
            [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
            [request setHTTPBody:post];
            [request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
            [request setTimeoutInterval:30];
            NSOperationQueue *queue = [[NSOperationQueue alloc] init];
            [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse* theResponse, NSData* theData, NSError* error){
                //Do whatever with return data

                NSString *result = [[NSString alloc] initWithData:theData encoding:NSUTF8StringEncoding];
                NSLog(@"Result : %@",result);
            }];

我想在 PHP 中检索该数组。我怎样才能做到这一点?

这是我尝试过但返回 null 的 php:

$handle = fopen('php://input','r');
$jsonInput = fgets($handle);
// Decoding JSON into an Array
$decoded = json_decode($jsonInput,true);

echo json_encode($decoded);
4

1 回答 1

0

我使用了一个稍微不同的Content-Type(这无关紧要):

[request addValue:@"text/json; charset=utf-8" forHTTPHeaderField:@"Content-Type"];

我也使用了稍微不同的 PHP:

<?php

$handle = fopen("php://input", "rb");
$http_raw_post_data = '';
while (!feof($handle)) {
    $http_raw_post_data .= fread($handle, 8192);
}
fclose($handle); 

$json_data = json_decode($http_raw_post_data, true);

echo json_encode($json_data);

?>

如果你得到一个空白响应,我敢打赌你有一些 PHP 错误。我希望您查看服务器的错误日志,或临时更改display_errorsphp.ini 中的设置,如下所示:

display_errors = On
于 2013-06-10T11:56:43.667 回答