PHP - 通过file_get_contents发布JSON

时间:2012-07-03 21:33:01

标签: php json rest post file-get-contents

我正在尝试将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;

3 个答案:

答案 0 :(得分:22)

这是我一直使用的代码,它看起来很相似(虽然这当然是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);
}

答案 1 :(得分:5)

的早期回应
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'。=(dot等于追加到数组元素。)

答案 2 :(得分:0)

问题是关于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] = self::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;
}

查看我的存储库以获取更多详细信息,https://github.com/Eugene-Melbourne/-HTTP_client-