curl基礎教程

對於http調試,curl是一個很好用的工具,本篇文章主要記錄curl平常的使用方法。html

訪問urljson

$ curl http://www.baidu.com
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100   251  100   251    0     0   7843      0 --:--:-- --:--:-- --:--:--  7843<HTML><HEAD><meta http-equiv="content-type" content="text/html;charset=gb2312"><TITLE>302 Moved</TITLE></HEAD><BODY><H1>302 Moved</H1>The document has moved<A HREF="http://www.baidu.com/?tn=28035039_3_pg&ld=www.baidu.com/">click here</A></BODY></HTML>

最基本的使用方法,訪問一個url,輸出返回結果。服務器

get參數
curl默認使用get方式訪問url,因此能夠直接在url後添加參數cookie

curl http://localhost:8080/hello?name=bin\&content=hello

注意:url中用&拼接參數時,須要使用\&進行轉碼app

修改http header參數curl

curl -H "Accept-Language: zh-cn" -H "Accept: application/html"  http://www.baidu.com

上面栗子中經過-H修改http header參數,-H能夠使用屢次,以修改多個參數。工具

POST JSON
開發中咱們常須要使用POST JSON的方法來訪問咱們的服務器:post

curl -H 'Content-Type: application/json; charset=UTF-8'  \
-X POST -d '{"name":"binecy","content":"hello"}' \
http://localhost:8080/hello

-X POST 指定使用post提交
-d 添加post json內容ui

post表單參數
除了post json,咱們還經常須要post 表單的鍵值對參數url

curl -X POST  -d  'nam=bin&content=hello' \
http://localhost:8080/hello

cookie信息
開發中經常在cookie中攜帶用戶的登錄信息,因此訪問url時也要攜帶cookie信息:

curl -H 'Content-Type: application/json; charset=UTF-8' --cookie "admin_token=00000763aZQ8GP5U" \
-X POST -d '{"name":"binecy","content":"hello"}' \
http://localhost:8080/hello

經過--cookie 添加cookie信息,
--cookie也能夠寫爲-b

顯示http頭部信息
添加-v參數能夠讓curl顯示http的請求和響應的header信息,方便咱們調試

$ curl http://www.baidu.com -v
* Rebuilt URL to: http://www.baidu.com/
* timeout on name lookup is not supported
*   Trying 14.215.177.39...
* TCP_NODELAY set
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
  0     0    0     0    0     0      0      0 --:--:-- --:--:-- --:--:--     0* Connected to www.baidu.com (14.215.177.39) port 80 (#0)
> GET / HTTP/1.1
> Host: www.baidu.com
> User-Agent: curl/7.54.0
> Accept: */*
>
< HTTP/1.1 302 Found
< Location: http://www.baidu.com/?tn=28035039_3_pg&ld=www.baidu.com/
< Content-Type: text/html;charset=gb2312
< Pragma: no-cache
< Cache-Control: no-cache
< Connection: close
< Server: wys
< Content-Length: 251
<
{ [251 bytes data]
100   251  100   251    0     0  15687      0 --:--:-- --:--:-- --:--:-- 15687<HTML><HEAD><meta http-equiv="content-type" content="text/html;charset=gb2312"><TITLE>302 Moved</TITLE></HEAD><BODY><H1>302 Moved</H1>The document has moved<A HREF="http://www.baidu.com/?tn=28035039_3_pg&ld=www.baidu.com/">click here</A></BODY></HTML>
* Closing connection 0

好了,本篇文章比較簡單,但對於curl的平常使用,也基本足夠了。

相關文章
相關標籤/搜索