【问题标题】:PHP cURL send oauth2.0 access_token in header and POST json dataPHP cURL 在标头和 POST json 数据中发送 oauth2.0 access_token
【发布时间】:2014-11-28 16:21:13
【问题描述】:

我试图将我的 access_token 发送到 POST 标头中的 oauth2.0,同时在正文中发布 json。

所以我已经获得了我的 access_token,现在想用它来向 API 提交一些数据。

$token = array(
 "access_token" =>$test->access_token);

$data = array(
  "Action" =>"updateUser",
  "data" =>array('somedata' => 'somemoredata')
  );

// Submit some data
$test2=curl_req2($pageURL.$webroot."/api/v1/User.php",$token, $data , "POST");
print_r($test2);

curl_req2() 函数如下所示:

function curl_req2($path,$token,$data,$req)
{
    $ch = curl_init($path);
    $data = json_encode($data);

    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $req);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: Bearer ' . $token['access_token']));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $result = curl_exec($ch);
    //$result = json_decode($result);
    curl_close($ch);

    return $result;
}

如果我这样做,它似乎没有收到 json 代码。当我在服务器端print_r($_REQUEST) 时,它只返回一个空数组。如果我不 json_encode $data,我的数组会被正常返回。

然后我尝试在 curl 的 HTTPHEADER 数组中添加 'Content-Type: application/json','Content-Length: ' . strlen($data),但是 HTTP 标头中的授权不起作用。

有没有一种方法可以在 POST 标头中授权令牌,同时在 POST 正文中发送 json 数据?

【问题讨论】:

  • 添加内容类型标头不应与授权标头相互影响,除非这是服务的预期功能。请您通过更新问题中的代码向我们展示您是如何添加 Content-Type 标头的吗?

标签: php json post curl oauth-2.0


【解决方案1】:

服务器的$_REQUEST 超全局适用于query strings,而不适用于 JSON 数据。

如果要访问请求正文,可以使用:

$json = file_get_contents("php://input");
$data = json_decode($json);
var_dump($data);

【讨论】:

    猜你喜欢
    • 2021-11-13
    • 2021-05-05
    • 2010-11-08
    • 1970-01-01
    • 1970-01-01
    • 2018-07-12
    • 1970-01-01
    • 1970-01-01
    • 2018-12-21
    相关资源
    最近更新 更多