php - 使用 php 中的 curl 将 json 发布到 API
问题描述
我有这个问题,我尝试向一个 API 发送请求,这个 APPI 需要一个应用程序/json,所以我首先在邮递员中测试以查看结果并按预期工作,但是在我的代码中没有,接下来是我的代码,公共函数我的函数()
{ $req = '{ “myparams”:myvalues,“myparams”:myvalues,“myparams”:myvalues,“myparams”:{ “myparams”:myvalues,“myparams”:“myvalues”,“myparams”:“myvalues” , "myparams": myvalues }'; $jsonRequest = json_decode($req, TRUE); ;
try{
self::setWsdl('API url');
$context =[
'Content-Type: application/json',
'Accept: application/json',
];
self::setContext($context);
self::setRequest($jsonRequest);
return InstanceCurlClient::curlClientInit();
} catch(\Exception $error){
return $error->getMessage();
}
}
然后让我的 curl 配置
public static function curlClientInit(){
try{
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_URL, self::getWsdl());
curl_setopt($ch, CURLOPT_FAILONERROR, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, self::getContext());
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_POSTFIELDS, self::getRequest());
$response = curl_exec($ch);
return $response;
}catch(\Exception $error) {
if (empty($response)) {
throw new SoapFault('CURL error: '.curl_error($ch), curl_errno($ch));
}
}
curl_close($ch);
}
所以我的结果如果我测试这个返回给我一个0并且我期望这个错误{“错误”:“Credenciales no válidas”}并且如果过去一个关联数组实例是一个json并且我使用json_enconde所以返回false我现在不知道为什么如果在邮递员中做同样的事情,我会给出我预期的错误原因
解决方案
如果您正在访问 JSON api,则使用 json_encode 而不是为 CURL_POSTFIELDS 放入数组是正确的。
如果您没有为数据设置正确的 $options 标志,内置的 json_encode 函数通常无法对数据进行编码。这实际上很烦人。
当它返回 false 时,您可以调用json_last_error_msg()
以了解它无法对您的数据进行编码的原因。这有望让我们更深入地研究这个问题。
推荐阅读
- python - 使用烧瓶时无法执行原始sql
- javascript - 功能应该是什么类型?
- javascript - 如何在 PHP 中设置下载路径
- c - 简单 C - 提取变量的即时值并将其存储
- scala - 释放从 ConnectionPool 借来的 Connection
- c# - 如何在 sql-server 中自动递增非整数主键?
- c++ - 是否可以在不使用模板的情况下在函数中从向量父 * 转换为向量子 *
- blockchain - 如何使用corda设计银行间支付系统
- r - 在闪亮的反应中过滤和聚类 SpatialPointDataFrame 不起作用
- javascript - 渲染完成的花式树事件