1

以下は、NSmutable Array を PHP Web サービスに送信する 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でその配列を取得したい。どうやってやるの?

これが私が試したphpですが、nullを返します:

$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_errors次のように php.ini の設定を一時的に変更してください。

display_errors = On
于 2013-06-10T11:56:43.667 に答える