【问题标题】:PHP cURL, POST JSON getting error in php curlPHP cURL,POST JSON 在 php curl 中出现错误
【发布时间】:2016-08-29 17:04:25
【问题描述】:
curl  -H "Accept: application/json" -H "Content-type: application/json" -X POST -d '{"firstname":"Mike","lastname":"Doel","customer_id":"12345","email":"test_api_user@gmail.com.com"}' -u API-key:  APIURL(http://)

上面的语句在命令中运行良好,但我无法通过 php 代码实现同样的效果,下面是我的代码

$url="https://apiurl"; 

$data=array("firstname"=>"Mike","lastname"=>"Doel","customer_id"=>"12345","email"=>"test_api_user@gmail.com");

$data_json=json_encode($data); 

//Curl code

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json',"Accept: application/json","api-key")); 
curl_setopt($ch, CURLOPT_POST, 1); 
curl_setopt($ch, CURLOPT_POSTFIELDS,$data_json); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
$response = curl_exec($ch);
curl_close($ch);

【问题讨论】:

标签: php json curl


【解决方案1】:
In CURL, for api key you need to pass username:password , if you going to access in php code 

$url="https://apiurl"; 
$curl = curl_init();
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);

curl_setopt_array($curl, array(
        CURLOPT_URL => $url,
        CURLOPT_HTTPAUTH => CURLAUTH_BASIC,
        CURLOPT_USERPWD => 'username:password',
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => "",
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 300000,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => 'POST',
        CURLOPT_HTTPHEADER => array(
            "accept: application/json",
            "content-type: application/json"
        ),
    CURLOPT_POSTFIELDS => $postfields,
));

$response = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);

return $response;

尝试一次..希望它对你有用。

【讨论】:

    【解决方案2】:

    这个:

     curl_setopt($ch, CURLOPT_HTTPHEADER, array([..snip..], "api-key")); 
                                                              ^^^^^
    

    curl [..snip..] -u api-key
                    ^^^^^^^^^^
    

    等价。 -u 指定 HTTP 基本身份验证,username:password。您的 setopt 只是将该用户名填充为 http 标头的名称,这不是基本身份验证凭据的显示方式

    你应该有

    curl_setopt($ch, CURLOPT_USERNAME, "api-key");
    

    改为。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-01-26
      • 2021-05-05
      • 2016-05-17
      • 2015-04-02
      • 2015-08-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多