28

我正在尝试将 JSON 内容发布到远程 REST 端点,但是“内容”值在交付时似乎为空。所有其他标头等都被正确接收,并且 Web 服务使用基于浏览器的测试客户端成功测试。

我在下面指定“内容”字段的语法是否有问题?

$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)。也许你username:key需要base64_encode'd。

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);}

是不正确的。此功能有时有效,但如果您不使用 application/x-www-form-urlencoded 的 Content-type 并传入用户名和密码,它会不准确并且会失败。

它对作者有用,因为 application/x-www-form-urlencoded 是默认的内容类型,但他对用户名和密码的处理覆盖了之前的内容类型声明。

这是修正后的函数:

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 回答