[英]json post to an API using curl in php
我有这个问题,我尝试向一个 API 发送请求,这个 APPI 需要一个应用程序/json,所以我首先在 postman 中测试以查看结果并按预期工作,但在我的代码中,下一个我的代码,公共 ZC1C476861AFD384510F2CB80CCFA8511Z我的函数()
{ $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,我现在不知道为什么如果在 postman 中做同样的事情,我会给出我预期的错误原因
如果您正在访问 JSON api,则使用 json_encode 而不是为 CURL_POSTFIELDS 放入数组是正确的。
如果您没有为数据设置正确的 $options 标志,内置的 json_encode function 通常无法对数据进行编码。 这实际上很烦人。
当它返回 false 时,您可以调用json_last_error_msg()
来了解它无法对您的数据进行编码的原因。 这有望让我们更深入地研究这个问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.