dtcu5885 2014-11-06 00:05
浏览 1067
已采纳

在PHP中使用cURL和x-www-form-urlencoded进行POST返回Access Denied

I have been able to use the Advanced Rest Client Extension for chrome to send POST queries to an specific HTTPS server and I get Status Code: 200 - OK with the same body fields as the ones I used in this code, but when I run the following code I get this response: 403 - Access Denied.

<?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'];
?>

I've noticed as well that when I use Advanced Rest Client Extension for chrome and if I set the Content-Type to application/json I have to enter a login and a password that I don't know what are those because even if I enter the id and secret key that I have in the code it returns 401 Unauthorized. So I'm guessing this code that I wrote is not forcing it to the content-type: application/x-www-form-urlencoded, but I'm not sure. Thank you for any help on this issue!

  • 写回答

1条回答 默认 最新

  • douguanci9158 2014-11-06 05:36
    关注

    Can you try like that and see if it helps:

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

    I guess the site expect simple authentication on top of the secret_key that you already provided.
    Also it is possible to send a Cookie, so just in case it is good idea to store it and use it again in the next Curl calls.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 求帮我调试一下freefem代码
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图