Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/244.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用PHP中的cURL和x-www-form-urlencoded返回访问被拒绝的POST_Php_Post_Curl - Fatal编程技术网

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

使用PHP中的cURL和x-www-form-urlencoded返回访问被拒绝的POST,php,post,curl,Php,Post,Curl,我已经能够使用针对chrome的高级Rest客户端扩展向特定HTTPS服务器发送POST查询,我得到的状态代码是:200-OK,与我在代码中使用的主体字段相同,但当我运行以下代码时,我得到的响应是:403-拒绝访问 <?php $postData = array( 'type' => 'credentials', 'id' => 'exampleid', 'secret_key' => 'gsdDe32dKa' ); // Setup cURL $ch = curl_i

我已经能够使用针对chrome的高级Rest客户端扩展向特定HTTPS服务器发送POST查询,我得到的状态代码是:200-OK,与我在代码中使用的主体字段相同,但当我运行以下代码时,我得到的响应是: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'];
?>


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

你能试试这样做,看看是否有帮助:

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),
));
我猜该网站希望在您已经提供的
密钥
上进行简单的身份验证。

此外,还可以发送Cookie,以防存储Cookie并在下一次Curl调用中再次使用它是个好主意。

我只是想知道为什么您要将我的代码“json\u encode($postData)”中的内容更改为“http\u build\u query()”。顺便说一下,我试图使用CURLOPT_USERPWD,但我得到了相同的错误。我想知道这两种方法中的哪一种发送的值是格式为json_encode还是http_build_查询?非常感谢WhayTanks的帮助,像
json\u encode
这样的东西在我的情况下效果更差!