【问题标题】:PHP api cURL POST How to get response?PHP api cURL POST 如何获得响应?
【发布时间】:2023-01-29 20:53:00
【问题描述】:

我正在尝试使用 cURL 通过 POST 请求验证 api 数据,但没有得到任何响应。 API documentation

<?php

$url = "https://widget.packeta.com/v6/api/pps/api/widget/validate";

$data = array(
    "Parameters" => array(
    "apiKey" => "XXXXXX",
    "id" => "9346",
    )
);

$encoded = json_encode($data);
$ch = curl_init($url);

curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $encoded);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$resp = curl_exec($ch);

$decoded = json_decode($resp);
print_r($decoded);

curl_close($ch);

?>

有谁知道出了什么问题?

【问题讨论】:

  • $decoded = json_decode($resp);你确定你收到的是有效的 JSON 吗?请做一个var_dump($resp)
  • 尝试添加这个选项:curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

标签: php api curl


【解决方案1】:

解决方案: 原来我缺少 CURL_HTTPHEADER。

curl_setopt($ch, CURLOPT_HTTPHEADER, array(
  "Content-Type: application/json",
  "Accept: application/json"
));

【讨论】:

    【解决方案2】:

    尝试写:

    $ch = curl_init();
    

    代替 :

    $ch = curl_init($url);
    

    最终你可以使用 try ... catch 来获取错误:

    <?php
    
    // Define variables
    define('API_KEY', 'XXXXXX');
    $url = "https://widget.packeta.com/v6/api/pps/api/widget/validate";
    $id = "9346";
    
    // Prepare data
    $data = array(
        "Parameters" => array(
            "apiKey" => API_KEY,
            "id" => $id,
        )
    );
    $encoded = json_encode($data);
    
    try {
        // Initialize cURL
        $ch = curl_init();
        
        // Set cURL options
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $encoded);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        
        // Execute cURL request
        $resp = curl_exec($ch);
        if($resp === false) {
            throw new Exception(curl_error($ch));
        }
        
        // Decode response and print it
        $decoded = json_decode($resp);
        print_r($decoded);
        
        // Close cURL session
        curl_close($ch);
    } catch (Exception $e) {
        echo 'Error: ' . $e->getMessage();
    }
    ?>
    

    【讨论】:

      猜你喜欢
      • 2011-04-27
      • 2015-05-21
      • 1970-01-01
      • 2016-01-09
      • 1970-01-01
      • 1970-01-01
      • 2018-07-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多