0

以下の関数を使用して、fopen を使用して POST 経由で JSON データを送信しようとしています。

function doPostRequest($url, $data, $optional_headers = null)
{
    $params = array(
        'http' => array(
            'method'  => 'POST',
            'content' => $data,
            'header'  => 'Content-type: application/json' . "\r\n"
                       . 'Content-Length: ' . strlen($data) . "\r\n"
        )
    );

    if ($optional_headers !== null) {
        $params['http']['header'] = $optional_headers;
    }

    $ctx = stream_context_create($params);

    try {
        $fp = fopen($url, 'rb', false, $ctx);

        $response = stream_get_contents($fp);
    } catch (Exception $e) {
        echo 'Exception: ' . $e->getMessage ();
    }

    return $response;
}

$json_data = array(
    'first_name' => 'John',
    'last_name'  => 'Doe'
);

$content = urlencode(json_encode($json_data));

doPostRequest($url, $content);

エラーは発生しませんが、データをデコードしようとする$input_streamと空になります。なんで?私は何が欠けていますか?

$input_stream = file_get_contents('php://input');
$json = urldecode($input_stream);
var_dump($input_stream);

編集: コードは XAMPP がインストールされているマシンでは動作しますが、別のマシンでは動作しません。サーバーの構成が関係している可能性はありますか?

4

2 に答える 2

0

その理由は、データのエンコード方法と Content-type の設定方法にあると思います。

Content-type: application/jsonで送信する場合は、データをurlencodeしないでください。

application/jsonapplication/x-www-form-urlencodedの違いについては、こちらを参照してください。

于 2013-04-03T18:30:22.720 に答える
0

問題は、$contentfromdoPostRequest($url, $content);が UTF-8 でエンコードされておらずいくつかの奇妙な文字がjson_decodeあったため、壊れていたという事実でした。

json_decode男によると:

この関数は、UTF-8 でエンコードされた文字列でのみ機能します。

于 2014-12-01T23:35:45.090 に答える