php - CURL POST 请求不适用于标头
问题描述
我试图向这个 API 发送一个发布请求,
"error": "unauthorized", "error_description": "An Authentication object was not found in the SecurityContext"
当我用邮递员发送相同的请求时它会返回给我,它工作正常。
这是我正在使用的代码
$url = config('payhere.cancel_url');
$postRequest = array(
'subscription_id'=>$payhereID
);
$headers = array(
'Authorization' =>'Bearer '.$accessToken,
'Content-Type'=>'application/json'
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
// SSL important
curl_setopt($ch,CURLOPT_POST,1);
curl_setopt($ch,CURLOPT_POSTFIELDS,$postRequest);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$output = curl_exec($ch);
curl_close($ch);
$respo = $this -> response['response'] = json_decode($output);
解决方案
标头应定义为数组,而不是关联数组。
此外,由于您已将 Content-Type 设置为application/json
,因此您的请求数据应表示为 JSON,这可以使用json_encode
.
$url = config('payhere.cancel_url');
$postRequest = array(
'subscription_id'=>$payhereID
);
$headers = array(
'Authorization: Bearer '.$accessToken,
'Content-Type: application/json'
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
// SSL important
curl_setopt($ch,CURLOPT_POST,1);
curl_setopt($ch,CURLOPT_POSTFIELDS,json_encode($postRequest));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$output = curl_exec($ch);
curl_close($ch);
$respo = $this->response['response'] = json_decode($output);
推荐阅读
- php - Laravel 表单获取非对象
- sql - 检索拥有多于一笔贷款的客户
- soapui - SOAP UI 详细报告
- mongodb - 如何在 MongoDB 中查找最新的文档?
- python - 多龙卷风 websocket 互相阻塞
- r - 将特定值转换为 R 中的列
- jboss - Infinispan 集群同步问题
- spring - 如何在 Spring 的 HandlerInterceptor 中获取原始处理程序 URI(带有通配符等)?
- tfs - Why one can set TFS predefined variables when they are said to be read-only?
- amazon-web-services - 启用 AWS Classic ELB 的跨区域负载平衡如何影响应用程序性能?