28

JSONコンテンツをリモートRESTエンドポイントにPOSTしようとしていますが、配信時に「content」値が空のように見えます。他のすべてのヘッダーなどは正しく受信されており、Webサービスはブラウザーベースのテストクライアントで正常にテストされています。

'content'フィールドを指定する以下の構文に問題がありますか?

$data = array("username" => "duser", "firstname" => "Demo", "surname" => "User", "email" => "example@example.com");   
$data_string = json_encode($data);

$result = file_get_contents('http://test.com/api/user/create', null, stream_context_create(array(
'http' => array(
'method' => 'POST',
'header' => array('Content-Type: application/json'."\r\n"
. 'Authorization: username:key'."\r\n"
. 'Content-Length: ' . strlen($data_string) . "\r\n"),
'content' => $data_string)
)
));

echo $result;
4

3 に答える 3

19

これは私がいつも使用しているコードであり、非常によく似ています(もちろん、これはx-www-form-urlencodedの場合です)。おそらくあなたは'dusername:keyである必要があります。base64_encode

function file_post_contents($url, $data, $username = null, $password = null)
{
    $postdata = http_build_query($data);

    $opts = array('http' =>
        array(
            'method'  => 'POST',
            'header'  => 'Content-type: application/x-www-form-urlencoded',
            'content' => $postdata
        )
    );

    if($username && $password)
    {
        $opts['http']['header'] = ("Authorization: Basic " . base64_encode("$username:$password"));
    }

    $context = stream_context_create($opts);
    return file_get_contents($url, false, $context);
}
于 2012-07-03T21:41:57.343 に答える
11

質問はについてでしたjson、なぜ受け入れられた答えはについてx-www-formですか?

Json苦労するクールなものがたくさんありますutf8_encode

function my_utf8_encode(array $in): array
{
    foreach ($in as $key => $record) {
        if (is_array($record)) {
            $in[$key] = my_utf8_encode($record);
        } else {
            $in[$key] = utf8_encode($record);
        }
    }

    return $in;
}


function file_post_contents(string $url, array $data, string $username = null, string $password = null)
{
    $data     = my_utf8_encode($data);
    $postdata = json_encode($data);
    if (is_null($postdata)) {
        throw new \Exception('decoding params');
    }

    $opts = array('http' =>
        array(
            'method'  => 'POST',
            'header'  => 'Content-type: application/json',
            'content' => $postdata
        )
    );

    if (!is_null($username) && !is_null($password)) {
        $opts['http']['header'] .= "Authorization: Basic " . base64_encode("$username:$password");
    }

    $context = stream_context_create($opts);

    try {
        $response = file_get_contents($url, false, $context);
    } catch (\ErrorException $ex) {

        throw new \Exception($ex->getMessage(), $ex->getCode(), $ex->getPrevious());
    }
    if ($response === false) {

        throw new \Exception();
    }

    return $response;
}
于 2020-08-24T05:35:09.307 に答える
4

の以前の応答

function file_post_contents($url, $data, $username = null, $password = null) {
$postdata = http_build_query($data);

$opts = array('http' =>
    array(
        'method'  => 'POST',
        'header'  => 'Content-type: application/x-www-form-urlencoded',
        'content' => $postdata
    )
);

if($username && $password)
{
    $opts['http']['header'] = ("Authorization: Basic " . base64_encode("$username:$password"));
}

$context = stream_context_create($opts);
return file_get_contents($url, false, $context);}

間違っている。この関数は時々機能しますが、不正確であり、Content-type of application / x-www-form-urlencodedを使用しておらず、ユーザー名とパスワードを渡した場合は失敗します。

application / x-www-form-urlencodedがデフォルトのContent-typeであるため、ライターにとっては機能していますが、ユーザー名とパスワードの処理により、以前のコンテンツタイプの宣言が上書きされています。

修正された関数は次のとおりです。

function file_post_contents($url, $data, $username = null, $password = null){
$postdata = http_build_query($data);

$opts = array('http' =>
    array(
        'method'  => 'POST',
        'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
        'content' => $postdata
    )
);

if($username && $password)
{
    $opts['http']['header'] .= ("Authorization: Basic " . base64_encode("$username:$password")); // .= to append to the header array element
}

$context = stream_context_create($opts);
return file_get_contents($url, false, $context);}

次の行に注意してください:$ opts ['http'] ['header'。=(ドットは配列要素に追加するのと同じです。)

于 2016-03-02T17:04:53.627 に答える