0

編集:データは問題なく送信されていたことがわかりましたが、PHP で本文を表示すると正しく動作しませんでした。詳細については、私の回答を参照してください。

json データをサーバーに投稿しようとしています。必要なのは、コンテンツ タイプを json にし、本文に json 形式の文字列を含めることだけです。私の問題は、コンテンツ タイプが text/html のままであり、何を試してもそのコンテンツ タイプを変更できないことです。私は多数のスタックオーバーフローの回答を読みましたが、それらはすべて機能するはずですが、機能しません。私のコードは以下です。

  $ch = curl_init($url);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
  curl_setopt($ch, CURLOPT_HEADER, 1);
  curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json"));      
  curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
  curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
  curl_exec($ch);

受信側では、getallheaders と get_file_contents('file://phpinput') を出力するだけです。

content-type が正しく処理されないのはなぜですか?

これが役立つ場合の出力例を次に示します。

string 'HTTP/1.1 200 OK
Date: Wed, 17 Apr 2013 16:24:56 GMT
Server: Apache/2.2.22 (Unix) mod_ssl/2.2.22 OpenSSL/0.9.8r DAV/2 PHP/5.4.4
X-Powered-By: PHP/5.4.4
Content-Length: 71
Content-Type: text/html

Array{"level1a":{"level2":{"a":2,"b":3}},"level2b":["111","333","999"]}' (length=273)
4

2 に答える 2

1

クライアント (client.php) とサーバー (server.php) の 2 つの php ファイルを作成する必要があります。

サーバーは json リクエストを読み取り、(json) レスポンスを返します。クライアントは json をサーバーに送信し、応答を読み取ります。

server.php は Web サーバーで利用できる必要がありますhttp://localhost/server.php。同じサーバーまたは別のサーバーからクライアントを実行できますhttp://localhost/client.php。コマンドラインからクライアントを実行することもできますphp -f client.php

サーバー.php:

<?
// read json input
$input = json_decode(file_get_contents('php://input'));
$response = array('text'=>'Your name is: '.$input->{'name'});
header("Content-type: application/json");
// send response
echo json_encode($response);
exit;

client.php:

<?
$data = array('name'=>'Jason'); // input
$ch = curl_init('http://localhost/server.php');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json"));      
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
$result = curl_exec($ch);
curl_close($ch);
list($headers, $content) = explode("\r\n\r\n", $result, 2);
$php = json_decode($content);
echo 'Response: ' . $php->text;
// if you want to know
var_dump($headers);
exit;
于 2013-04-17T22:30:39.110 に答える