Curl Command

Curl 指令基本介紹與常見用法

Curl 是一個在 Linux 上用來透過 HTTP Protocol(HTTP HyperText Transfer Protocol 定義存取網路資源的協定,讓我們可以使用 client / server 模式來取得網路資源)下載和上傳檔案的指令(比起 wget 只能下載強大許多)。它基本的指令格式如下:

curl [options] [URL...]

打開終端機(terminal)然後,curl 後面加網址,就會在終端機內顯示回傳的 response,可能是 HTML、JSON 或是 XML 等格式,根據輸入的 URL 內容而定。

curl https://www.baidu.com

下载:

下載:可以使用 -o 搭配欲下載的檔名和網址;

curl -o vue.png https://cn.vuejs.org/images/logo.png

若是使用 -O 則可以直接使用下載網址的檔案檔名來命名下載的檔案;

curl -O https://cn.vuejs.org/images/logo.png

有可能在下載過程中被中斷,若是想要從中斷的地方繼續的話,可以使用 -C 選項:

curl -C - -O http://releases.ubuntu.com/18.04/ubuntu-18.04-desktop-
amd64.iso

若希望可以跟隨著網址 301/302 redirect 的話,可以使用 -L 選項:

curl -L http://google.com

若我們要追蹤整個 curl 過程,並將結果存入 debugdump.txt 檔案可以使用 –trace-ascii 指令:

curl --trace-ascii debugdump.txt http://www.example.com/

使用 Curl 來進行 HTTP Request

除了簡易的下載檔案或是取得網頁內容外,Curl 還支援各種不同 HTTP 請求方法(HTTP method),以下列出常用指令和選項參數:

参数 详情
-X/–request [GET|POST|PUT|DELETE|PATCH] 使用指定的 http method 來發出 http request
-H/–header 設定 request 裡所攜帶的 header
-i/–include 在 output 顯示 response 的 header
-d/–data 攜帶 HTTP POST Data
-v/–verbose 輸出更多的訊息方便 debug
-u/–user 攜帶使用者帳號、密碼
-b/–cookie 攜帶 cookie(可以是參數或是檔案位置)

1. GET

簡易一個 URL 版本,可以攜帶 query string 參數取得網路資源:

$ curl https://example.com?q1=123&q2=abc

在同一個指令使用多個 URL:

$ curl http://example1.com http://example2.com

2. Form POST

一般而言我們 Form 表單的 HTML 會長這樣:

<form method="POST" action="form.php">
   <input type=text name="email">
   <input type=submit name=press value=" OK ">
</form>

由於 Form post 是使用 application/x-www-form-urlencoded Content-Type,所以傳遞的值需要編碼:

$ curl -X POST --data "email=test@example.com&press=%20OK%20" http://
www.example.com/form.php

3. File Upload POST

另一種常見 Form 表單是有涉及檔案上傳(使用 multipart/form-data Content-Type):

<form method="POST" enctype='multipart/form-data' action="upload.php">
 <input type=file name=upload>
 <input type=submit name=press value="OK">
</form>

可以看到指令會需要攜帶 upload 檔案:

curl -X POST -F 'file=@./upload.txt' http://www.example.com/upload.php

4. 常見 Restful CRUD 指令:

$ curl -X GET "http://www.example.com/api/resources"
$ curl -X GET "http://www.example.com/api/resources/1"
$ curl -X POST -H "Content-Type: application/json" -d '{"status" : 
false, "name" : "Jack"}' "http://www.example.com/api/resources"
curl -X PUT -H "Content-Type: application/json" -d '{"status" : false 
}' "http://www.example.com/api/resources"
$ curl -X DELETE "http://www.example.com/api/resources/1"
$ curl --cookie "name=Jack" http://www.example.com
$ curl --cookie stored_cookies_file_path http://www.example.com
$ curl --user-agent "Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0
)" http://www.example.com
$ curl -i --user secret:vary_secret http://www.example.com/api/resources