PHP - 通过file_get_contents发布 JSON

2022-08-30 15:18:37

我正在尝试将 JSON 内容发布到远程 REST 终结点,但“内容”值在交付时显示为空。所有其他标头等都被正确接收,并且 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;

答案 1

这是我经常使用的代码,它看起来非常相似(尽管这当然是针对x-www-form-urlencoded的)。也许你需要被'd。username:keybase64_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);
}

答案 2

问题是关于,为什么接受的答案是关于?jsonx-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;
}

推荐