在 PHP 中使用 cURL 和 x-www-form-urlencoded POST 返回拒绝访问

VaT*_*aTo 3 php post curl

我已经能够使用 chrome 的 Advanced Rest Client Extension 将 POST 查询发送到特定的 HTTPS 服务器,并且我得到状态代码:200 - 使用与我在此代码中使用的相同的正文字段,但是当我运行下面的代码我得到这个响应:403 - 拒绝访问。

<?php
$postData = array(
'type' => 'credentials',
'id' => 'exampleid',
'secret_key' => 'gsdDe32dKa'
);

// Setup cURL
$ch = curl_init('https://www.mywebsite.com/oauth/token');
curl_setopt_array($ch, array(
CURLOPT_POST => TRUE,
CURLOPT_RETURNTRANSFER => TRUE,
CURLOPT_HTTPHEADER => array('Content-Type: application/x-www-form-urlencoded'
),
CURLOPT_POSTFIELDS => json_encode($postData)
));

// Send the request
$response = curl_exec($ch);

var_dump($response);

// Check for errors
if($response === FALSE){
die(curl_error($ch));
}

// Decode the response
$responseData = json_decode($response, TRUE);

// Print the date from the response
echo $responseData['published'];
?>
Run Code Online (Sandbox Code Playgroud)

我也注意到,当我对 chrome 使用 Advanced Rest Client Extension 时,如果我将 Content-Type 设置为 application/json,我必须输入登录名和密码,我不知道这些是什么,因为即使我输入我在代码中拥有的 ID 和密钥,它返回 401 Unauthorized。所以我猜我写的这段代码并没有强迫它使用内容类型:application/x-www-form-urlencoded,但我不确定。感谢您对这个问题的任何帮助!

Ant*_*kov 7

你可以这样尝试,看看它是否有帮助:

curl_setopt_array($ch, array(
    CURLOPT_POST => TRUE,
    CURLOPT_RETURNTRANSFER => TRUE,
    CURLOPT_COOKIEFILE => 'cookie.txt',
    CURLOPT_COOKIEJAR => 'cookie.txt',
    CURLOPT_USERPWD => 'username:password', //Your credentials goes here
    CURLOPT_HTTPHEADER => array('Content-Type: application/x-www-form-urlencoded'),
    CURLOPT_POSTFIELDS => http_build_query($postData),
));
Run Code Online (Sandbox Code Playgroud)

我猜该网站希望在secret_key您已经提供的基础上进行简单的身份验证。
也可以发送 Cookie,以防万一最好存储它并在下一次 Curl 调用中再次使用它。