Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學
您现在的位置: Windows教程網 >> Windows教程 >  >> Linux 系統教學 >> Linux 教學

Linux cURL 命令行實戰:POST 數據、文件上傳、JSON API 調用

編輯:Linux 教學

cURL 是命令行下最強大的 HTTP 客戶端工具,支援多種協議與認證方式。本文聚焦 POST 請求的常見場景:表單數據、文件上傳、JSON API 調用。

基本 POST 請求

# application/x-www-form-urlencoded 表單提交
curl -d "param1=value1¶m2=value2" https://example.com/api

# 從文件讀取 POST 數據(自動設置 Content-Type)
curl -d @data.txt https://example.com/api

文件上傳

# 單文件上傳(multipart/form-data)
curl -F "file=@/path/to/local/file.zip" https://example.com/upload

# 多文件上傳
curl -F "file1=@/path/a.jpg" -F "file2=@/path/b.pdf" https://example.com/upload

# 指定文件名與 MIME 類型
curl -F "file=@/path/data.csv;filename=report.csv;type=text/csv" https://example.com/upload

JSON API 調用

# 發送 JSON 數據
curl -H "Content-Type: application/json" \
     -d '{"id":1,"name":"test","amount":99.9}' \
     https://example.com/api/resource

# 從文件發送 JSON
curl -H "Content-Type: application/json" \
     -d @payload.json \
     https://example.com/api/resource

# 陣列格式
curl -H "Content-Type: application/json" \
     -d '[{"id":1,"money":100},{"id":2,"money":200}]' \
     https://example.com/api/batch

認證與會話

# Basic Auth
curl -u username:password -d "data" https://example.com/api

# Bearer Token
curl -H "Authorization: Bearer YOUR_TOKEN" -d "data" https://example.com/api

# Cookie 會話保持
curl -c cookies.txt -d "login=xxx" https://example.com/login
curl -b cookies.txt -d "data" https://example.com/api

常用調試參數

  • -v:詳細輸出請求/響應頭
  • -i:輸出響應頭
  • -s:靜默模式(配合 -o 輸出文件)
  • -w:自定義輸出格式(如耗時、狀態碼)
    curl -w "\nHTTP %{http_code} | Time %{time_total}s\n" -o /dev/null -s https://example.com
  • --max-time:最大超時秒數
  • --retry:失敗重試次數

實用技巧

# 斷點續傳下載
curl -C - -O https://example.com/large.iso

# 限速下載
curl --limit-rate 500k -O https://example.com/file.zip

# 解析指定 IP(繞過 DNS)
curl --resolve example.com:443:1.2.3.4 https://example.com/

# 測試代理
curl -x socks5://127.0.0.1:1080 https://httpbin.org/ip

總結

掌握 -d、-F、-H 三大核心參數組合,即可應對 90% 的 API 調試場景。配合 jq 處理 JSON 響應,構建強大的命令行 API 工作流。

Copyright © Windows教程網 All Rights Reserved