Home | 簡體中文 | 繁體中文 | 雜文 | 知乎專欄 | Github | OSChina 博客 | 雲社區 | 雲棲社區 | Facebook | Linkedin | 視頻教程 | 打賞(Donations) | About

7.5. CURL - transfer a URL

7.5.1. 基本用法

		
curl http://www.google.com/		
		
		

7.5.2. 提交表單數據

post 表單數據

		
curl -d "user=neo&password=chen" http://www.example.com/login.php
curl --data "user=neo&password=chen" http://www.example.com/login.php
		
		

7.5.3. 上傳檔案

		
curl  -F "upload=@card.txt;type=text/plain"  "http://www.example.com/upload.php"		
		
		

使用 CURL 上傳 Oauth2 + Jwt 認證的 Restful 介面

		
curl -s  -H "Authorization: Bearer ${TOKEN}" -X POST -F "file=@/etc/hosts" http://localhost:8080/upload/single		
		
		

7.5.4. connect-timeout

		
curl -o /dev/null --connect-timeout 30 -m 30 -s -w %{http_code} http://www.google.com/		
		
		

7.5.5. max-time

-m, --max-time SECONDS Maximum time allowed for the transfer

			curl -o /dev/null --max-time 10 http://www.netkiller.cn/
		

7.5.6. compressed

--compressed Request compressed response (using deflate or gzip)

			curl --compressed http://www.example.com
		

7.5.7. vhosts

有時候你需要設覺察/etc/hosts檔案才能訪問vhost,下面例子可以不設置/etc/hosts

			curl -x 127.0.0.1:80 your.exmaple.com/index.php
		

socks5 伺服器

		
$ curl -v -x socks5://username:password@IP:1080 http://www.google.com/		
		
		

7.5.8. -w, --write-out <format> 輸出格式定義

			計時器 描述
			time_connect 建立到伺服器的 TCP 連接所用的時間
			time_starttransfer 在發出請求之後,Web 伺服器返回數據的第一個位元組所用的時間
			time_total 完成請求所用的時間
			time_namelookup DNS解析時間,從請求開始到DNS解析完畢所用時間(記得關掉 Linux 的 nscd 的服務測試)
			speed_download 下載速度,單位-位元組每秒。
		
			curl -o /dev/null -s -w %{time_connect}:%{time_starttransfer}:%{time_total} http://www.example.net
			curl -o /dev/null -s -w "Connect: %{time_connect}\nTransfer: %{time_starttransfer}\nTotal: %{time_total}\n" https://www.netkiller.cn/index.html

			curl -o /dev/null -s -w "Connect: %{time_connect} \nTransfer: %{time_starttransfer}\nTotal: %{time_total}\nNamelookup: %{time_namelookup}\nDownload: %{speed_download}\n" https://www.netkiller.cn/index.html
			Connect: 0.024241
			Transfer: 0.117727
			Total: 0.117842
			Namelookup: 0.004367
			Download: 129877.000
		

測試頁面所花費的時間

			date ; curl -s -w 'Connect: %{time_connect} TTFB: %{time_starttransfer} Total time: %{time_total} \n' -H "Host: www.example.com" http://172.16.0.1/webapp/test.jsp ; date ;
		
			curl -o /dev/null -s -w %{time_connect}, %{time_starttransfer}, %{time_total}, %{time_namelookup}, %{speed_download} http://www.netkiller.cn
		

返回HTTP狀態碼

			curl -s -I http://netkiller.sourceforge.net/ | grep HTTP | awk '{print $2" "$3}'
			curl -o /dev/null -s -w %{http_code} http://netkiller.sourceforge.net/

			curl --connect-timeout 5 --max-time 60 --output /dev/null -s -w %{response_code} http://www.netkiller.cn/
		
			# curl -w '\nLookup time:\t%{time_namelookup}\nConnect time:\t%{time_connect}\nPreXfer time:\t%{time_pretransfer}\nStartXfer time:\t%{time_starttransfer}\n\nTotal time:\t%{time_total}\n' -o /dev/null -s http://www.netkiller.cn

			Lookup time: 0.125
			Connect time: 0.125
			PreXfer time: 0.125
			StartXfer time: 0.125

			Total time: 0.126
		

7.5.9. -A/--user-agent <agent string>

設置用戶代理,這樣web伺服器會認為是其他瀏覽器訪問

			curl -A "Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)" http://www.example.com
		

7.5.10. referer

		
curl -v -o /dev/null -e "http://www.example.com" http://www.your.com/
* About to connect() to www.your.com port 80
*   Trying 172.16.1.10... connected
* Connected to www.your.com (172.16.1.10) port 80
> GET / HTTP/1.1
> User-Agent: curl/7.15.5 (x86_64-redhat-linux-gnu) libcurl/7.15.5 OpenSSL/0.9.8b zlib/1.2.3 libidn/0.6.5
> Host: www.your.com
> Accept: */*
> Referer: http://www.example.com
>
< HTTP/1.1 200 OK
< Date: Thu, 30 Sep 2010 07:59:47 GMT
< Server: Apache/2.2.16 (Unix) mod_ssl/2.2.16 OpenSSL/0.9.8e-fips-rhel5 PHP/5.2.14
< Accept-Ranges: bytes
< Transfer-Encoding: chunked
< Content-Type: text/html; charset=UTF-8
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100  172k    0  172k    0     0  10.2M      0 --:--:-- --:--:-- --:--:-- 11.9M* Connection #0 to host www.your.com left intact

* Closing connection #0
		
		

7.5.11. -v


		

7.5.12. -o, --output FILE Write output to <file> instead of stdout

			curl -o /dev/null http://www.example.com
			curl -o index.html http://www.example.com
		

7.5.13. -L, --location

		
curl -L --retry 5 --retry-delay 3 https://github.com/hyperledger/fabric/releases/download/v2.0.1/hyperledger-fabric-linux-amd64-2.0.1.tar.gz | tar xz		
		
		

7.5.14. -H/--header <line> Custom header to pass to server (H)

7.5.14.1. Last-Modified / If-Modified-Since

If-Modified-Since

			
neo@neo-OptiPlex-780:/tmp$ curl -I http://images.example.com/test/test.html
HTTP/1.0 200 OK
Cache-Control: s-maxage=7200, max-age=900
Expires: Mon, 16 May 2011 08:10:37 GMT
Content-Type: text/html
Accept-Ranges: bytes
ETag: "1205579110"
Last-Modified: Mon, 16 May 2011 06:57:39 GMT
Content-Length: 11
Date: Mon, 16 May 2011 07:55:37 GMT
Server: lighttpd/1.4.26
Age: 604
X-Via: 1.0 ls71:80 (Cdn Cache Server V2.0), 1.0 lydx136:8105 (Cdn Cache Server V2.0)
Connection: keep-alive

neo@neo-OptiPlex-780:/tmp$ curl -H
"If-Modified-Since: Fri, 12 May 2011 18:53:33 GMT" -I http://images.example.com/test/test.html
HTTP/1.0 304 Not Modified
Date: Mon, 16 May 2011 07:56:19 GMT
Content-Type: text/html
Expires: Mon, 16 May 2011 08:11:19 GMT
Last-Modified: Mon, 16 May 2011 06:57:39 GMT
ETag: "1205579110"
Cache-Control: s-maxage=7200, max-age=900
Age: 790
X-Via: 1.0 wzdx168:8080 (Cdn Cache Server V2.0)
Connection: keep-alive
			
			

7.5.14.2. ETag / If-None-Match

			
neo@neo-OptiPlex-780:/tmp$ curl -I http://images.example.com/test/test.html
HTTP/1.1 200 OK
Cache-Control: s-maxage=7200, max-age=900
Expires: Mon, 16 May 2011 09:48:45 GMT
Content-Type: text/html
Accept-Ranges: bytes
ETag: "1984705864"
Last-Modified: Mon, 16 May 2011 09:01:07 GMT
Content-Length: 22
Date: Mon, 16 May 2011 09:33:45 GMT
Server: lighttpd/1.4.26
			
			
			
neo@neo-OptiPlex-780:/tmp$ curl -H 'If-None-Match: "1984705864"' -I http://images.example.com/test/test.html
HTTP/1.1 304 Not Modified
Cache-Control: s-maxage=7200, max-age=900
Expires: Mon, 16 May 2011 09:48:32 GMT
Content-Type: text/html
Accept-Ranges: bytes
ETag: "1984705864"
Last-Modified: Mon, 16 May 2011 09:01:07 GMT
Date: Mon, 16 May 2011 09:33:32 GMT
Server: lighttpd/1.4.26
			
			

7.5.14.3. Accept-Encoding:gzip,defalte

			
$ curl -H Accept-Encoding:gzip,defalte -I http://www.example.com/product/374218.html
HTTP/1.1 200 OK
Date: Mon, 16 May 2011 09:13:18 GMT
Server: Apache
Accept-Ranges: bytes
Content-Encoding: gzip
Content-Length: 16660
Content-Type: text/html; charset=UTF-8
X-Pad: avoid browser bug
Age: 97
X-Via: 1.1 dg44:8888 (Cdn Cache Server V2.0)
Connection: keep-alive
			
			

			
$ curl -H Accept-Encoding:gzip,defalte http://www.example.com/product/374218.html | gunzip
			
			

7.5.14.4. HOST

			
curl -H HOST:www.example.com -I http://172.16.1.10/product/374218.html
			
			

7.5.14.5. HTTP 認證

未認證返回401

			
# curl --compressed http://webservice.example.com/members
<html>
<head><title>401 Authorization Required</title></head>
<body bgcolor="white">
<center><h1>401 Authorization Required</h1></center>
<hr><center>nginx</center>
</body>
</html>
			
			

-u/--user <user[:password]> Set server user and password

使用 -u或者 --user 指定用戶與密碼

				# curl --compressed -uneo:chen http://webservice.example.com/members
			

7.5.14.6. Accept

			
-H "Accept: application/json"		
			
			

7.5.14.7. Content-Type

			
-H "Content-Type: application/json"			
			
			

7.5.15. curl-config

		
curl-config --features
		
		

7.5.16. 指定網絡介面或者地址

--interface INTERFACE Use network INTERFACE (or address)

		
curl --interface 127.0.0.1 http://www.netkiller.cn		
		
		

7.5.17.  Cookie 處理

cookie 可以從 http header 設置

		
curl -LO -H "Cookie: oraclelicense=accept-securebackup-cookie" http://download.oracle.com/otn-pub/java/jdk/8u131-b11/d54c1d3a095b4ff2b6607d096fa80163/jdk-8u131-linux-x64.rpm
		
		

curl 還提供兩個參數用於處理 cookie

		
-b, --cookie STRING/FILE Read cookies from STRING/FILE (H) 讀取 cookie 檔案
-c, --cookie-jar FILE Write cookies to FILE after operation (H) 將 cookie 寫入檔案
		
		
		
curl -c cookie.txt -d "user=neo&password=123456" http://www.netkiller.cn/login
curl -b cookie.txt http://www.netkiller.cn/user/profile
		
		

7.5.18. Restful 應用 JSON 數據處理

下面提供一些使用 curl 操作 restful 的實例

GET 操作

		
curl http://api.netkiller.cn/v1/withdraw/get/15.json
		
		

用戶認證的情況

		
curl http://test:123456@api.netkiller.cn/v1/withdraw/get/id/815.json
		
		

POST 操作

		
curl -i -H "Accept: application/json" -H "Content-Type: application/json" -X POST -d '
{
"id":"B040200000000000000","name":"Neo","amount":12,"password":"12345","createdate":"2016-09-12 13:10:10"

}' https://test:123456@api.netkiller.cn/v1/withdraw/create.json
		
		
curl -H "Accept: application/json" -H "Content-Type: application/json" -d '{"id":100000, "username":"netkiller", "password":"123456", "email":"netkiller@msn.com"}' curl http://localhost:8080/restful/validation

7.5.18.1. Curl Oauth2

			
URL=https://api.netkiller.cn
token=$(curl -k --cacert -s -X POST --user 'api:secret' -d 'grant_type=password&username=netkiller@msn.com&password=123456' ${URL}/oauth/token | grep -o -E '"access_token":"([0-9a-f-]+)"' | cut -d \" -f 4 )
curl -k -H "Accept: application/json" -H "Content-Type: application/json" -H "Authorization: Bearer ${token}" -X GET ${URL}/search/article/list/22/0/5.json			
			
			

7.5.18.2. Curl + Oauth2 + Jwt

獲取 access_token 字元串

方法一

			
curl -s  -X POST --user 'api:secret' -d 'grant_type=password&username=netkiller@msn.com&password=123456' http://localhost:8080/oauth/token | sed 's/.*"access_token":"\([^"]*\)".*/\1/g'
			
			

方法二

			
curl -s  -X POST --user 'api:secret' -d 'grant_type=password&username=netkiller@msn.com&password=123456' http://localhost:8080/oauth/token | grep -o -E '"access_token":"(.+)"' | cut -d \" -f 4			
			
			

7.5.19. HTTP2

curl 已經支持 HTTP2,使用方法如下

		
neo@MacBook-Pro ~/workspace % curl -I --http2 https://www.google.com  
HTTP/2 200 
date: Tue, 26 Feb 2019 06:36:03 GMT
expires: -1
cache-control: private, max-age=0
content-type: text/html; charset=ISO-8859-1
p3p: CP="This is not a P3P policy! See g.co/p3phelp for more info."
server: gws
x-xss-protection: 1; mode=block
x-frame-options: SAMEORIGIN
set-cookie: 1P_JAR=2019-02-26-06; expires=Thu, 28-Mar-2019 06:36:03 GMT; path=/; domain=.google.com
set-cookie: NID=160=aQySEvsSa9gVU8qivD3t5qsgi_PRUtD5Ao3nRb48jMyLAzlYA1ViWuF1BaZHChVzY6EuknQ0OUz3Z2vhWwrclzO4WV6BmWgPhz6jowqFF3XCStsyYVwLQp2-_c0aGioBryAP1bTT0c-PX9iJzk5Zcbm2cFs6kH0Qb2a_3ML7Ioc; expires=Wed, 28-Aug-2019 06:36:03 GMT; path=/; domain=.google.com; HttpOnly
alt-svc: quic=":443"; ma=2592000; v="44,43,39"
accept-ranges: none
vary: Accept-Encoding		
		
		

HTTP/2 200 表示當前採用 HTTP2 連接

7.5.20. FAQ

Error in TLS handshake, trying SSLv3...

解決方案

		
curl -v --cipher rsa_rc4_128_sha https://www.mpaymall.com/MPay/MerchantPay.do