萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP cURL 發送 JSON 資料完整範例

呼叫 RESTful API 或微服務時,常需以 JSON 格式發送 POST 請求。本文提供完整可執行的 cURL 範例,涵蓋 Header 設定、錯誤處理、回應解析等實務細節。

基本發送範例

<?php
$url = 'https://api.example.com/endpoint';

// 要發送的資料陣列
$data = [
    'button' => [
        ['type' => 'click', 'name' => '今日歌曲', 'key' => 'V1001_TODAY_MUSIC'],
        ['type' => 'click', 'name' => '歌手簡介', 'key' => 'V1001_TODAY_SINGER'],
        [
            'name' => '菜單',
            'sub_button' => [
                ['type' => 'click', 'name' => 'hello world', 'key' => 'V1001_HELLO_WORLD'],
                ['type' => 'click', 'name' => '贊一下我們', 'key' => 'V1001_GOOD'],
            ],
        ],
    ],
];

$ch = curl_init($url);

// 核心設定
curl_setopt_array($ch, [
    CURLOPT_POST           => true,
    CURLOPT_POSTFIELDS     => json_encode($data, JSON_UNESCAPED_UNICODE),
    CURLOPT_HTTPHEADER     => [
        'Content-Type: application/json',
        'Accept: application/json',
    ],
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_TIMEOUT        => 10,
    CURLOPT_SSL_VERIFYPEER => true,  // 生產環境請保持 true
    CURLOPT_SSL_VERIFYHOST => 2,
]);

$response = curl_exec($ch);

if ($response === false) {
    $errno = curl_errno($ch);
    $error = curl_error($ch);
    curl_close($ch);
    throw new RuntimeException("cURL Error ($errno): $error");
}

$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

// 解析回應
$result = json_decode($response, true);
if (json_last_error() !== JSON_ERROR_NONE) {
    throw new RuntimeException('Invalid JSON response: ' . json_last_error_msg());
}

var_dump($httpCode, $result);
?>

關鍵選項說明

選項用途
CURLOPT_POSTFIELDS發送資料,JSON 需先 json_encode()
CURLOPT_HTTPHEADER必須含 Content-Type: application/json
CURLOPT_RETURNTRANSFER回傳字串而非直接輸出
CURLOPT_TIMEOUT總逾時秒數(含連線+傳輸)
CURLOPT_CONNECTTIMEOUT僅連線階段逾時
JSON_UNESCAPED_UNICODE避免中文被轉成 \uXXXX,節省頻寬

進階:可重用的 HttpClient 類別

<?php
class JsonHttpClient {
    private $baseUrl;
    private $defaultHeaders;
    private $timeout;

    public function __construct(string $baseUrl, int $timeout = 10) {
        $this->baseUrl = rtrim($baseUrl, '/');
        $this->timeout = $timeout;
        $this->defaultHeaders = [
            'Content-Type: application/json',
            'Accept: application/json',
            'User-Agent: MyApp/1.0 (+https://example.com)',
        ];
    }

    public function post(string $endpoint, array $data, array $extraHeaders = []): array {
        return $this->request('POST', $endpoint, $data, $extraHeaders);
    }

    public function get(string $endpoint, array $query = [], array $extraHeaders = []): array {
        $url = $this->baseUrl . $endpoint;
        if ($query) $url .= '?' . http_build_query($query);
        return $this->request('GET', $url, null, $extraHeaders);
    }

    private function request(string $method, string $url, ?array $data, array $extraHeaders): array {
        $ch = curl_init($url);
        $headers = array_merge($this->defaultHeaders, $extraHeaders);

        $options = [
            CURLOPT_CUSTOMREQUEST  => $method,
            CURLOPT_HTTPHEADER     => $headers,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT        => $this->timeout,
            CURLOPT_SSL_VERIFYPEER => true,
            CURLOPT_SSL_VERIFYHOST => 2,
        ];

        if ($data !== null) {
            $options[CURLOPT_POSTFIELDS] = json_encode($data, JSON_UNESCAPED_UNICODE);
        }

        curl_setopt_array($ch, $options);
        $response = curl_exec($ch);

        if ($response === false) {
            $errno = curl_errno($ch);
            $error = curl_error($ch);
            curl_close($ch);
            throw new RuntimeException("cURL $method $url failed ($errno): $error");
        }

        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        $result = json_decode($response, true);
        if (json_last_error() !== JSON_ERROR_NONE) {
            throw new RuntimeException("Invalid JSON from $url: " . json_last_error_msg());
        }

        if ($httpCode >= 400) {
            throw new RuntimeException("HTTP $httpCode: " . ($result['message'] ?? $response));
        }

        return $result;
    }
}

// 使用範例
$client = new JsonHttpClient('https://api.example.com');
try {
    $result = $client->post('/webhook', ['event' => 'order.created', 'payload' => [...]]);
    echo "Success: " . json_encode($result);
} catch (Throwable $e) {
    error_log($e->getMessage());
}
?>

常見坑點

  • 忘記 Content-Type:伺服器會以 form-data 解析導致參數為空
  • 雙重編碼:http_build_query(json_encode(...)) 錯誤用法
  • SSL 驗證關閉:生產環境絕不可 設 CURLOPT_SSL_VERIFYPEER = false
  • 大檔案上傳:JSON 不適合傳輸二進位,改用 multipart/form-data

總結

掌握 json_encode() + CURLOPT_HTTPHEADER + CURLOPT_POSTFIELDS 三要素,並善用封裝類別統一錯誤處理、逾時與重試邏輯,即能穩健串接各類 JSON API。

copyright © 萬盛學電腦網 all rights reserved