呼叫 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,節省頻寬 |
<?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());
}
?>
http_build_query(json_encode(...)) 錯誤用法CURLOPT_SSL_VERIFYPEER = false掌握 json_encode() + CURLOPT_HTTPHEADER + CURLOPT_POSTFIELDS 三要素,並善用封裝類別統一錯誤處理、逾時與重試邏輯,即能穩健串接各類 JSON API。