
正文
Linux:curl
提示:扫一扫查出行【扫一扫了解最新限行尾号】
复制提示
curl命令用来做HTTP协议的客户端,可以通过命令参数生成各种请求,非常强大。
1. GET
默认情况下下curl执行的是GET操作,所以可以当做wget使用如
$ curl https://www.baidu.com
<html>
<head>
<script>
location.replace(location.href.replace("https://","http://"));
</script>
</head>
<body>
<noscript><meta http-equiv="refresh" content="0;url=http://www.baidu.com/"></noscript>
</body>
现在百度使用了https协议,但是这个结果还是有点奇怪的,使用https地址却又想让你去访问http。但是浏览器直接输入https地址,观察网络情况却没有这个过程。所以可能是百度根据请求头的User-Agent做了一些判断。那么可以在命令中使用 -A 参数来指定User-Agent(chrome的UA字串)如:
$ curl https://www.baidu.com -A 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.118 Safari/537.36'
此时就会有百度首页的内容返回。
2. POST/PUT
如果不是进行GET请求需要在命令中另外指定请求类型使用 -X 参数如:
-XPUT
-XPOST
PUT和POST请求都是可以带请求体的,他们通过 -d 指定,另外使用 -v 参数可以打开verbose模式观察http协议通信情况:
$ curl -XPOST http://www.baidu.com/ -d 'a=1&p=1' -v
* Hostname was NOT found in DNS cache
* Trying 115.239.211.112...
* Connected to www.baidu.com (115.239.211.112) port (#)
> POST / HTTP/1.1
> User-Agent: curl/7.35.
> Host: www.baidu.com
> Accept: */*
> Content-Length: 7
> Content-Type: application/x-www-form-urlencoded
>
* upload completely sent off: 7 out of 7 bytes
< HTTP/1.1 302 Moved Temporarily
< Date: Wed, 03 Jun 2015 02:30:05 GMT
< Content-Type: text/html
< Content-Length: 215
< Connection: Keep-Alive
< Location: http://www.baidu.com/search/error.html
* Server BWS/1.1 is not blacklisted
< Server: BWS/1.1
< X-UA-Compatible: IE=Edge,chrome=1
< BDPAGETYPE: 3
< Set-Cookie: BDSVRTM=0; path=/
<
<html>
<head><title>302 Found</title></head>
<body bgcolor="white">
<center><h1>302 Found</h1></center>
<hr><center>pr-nginx_1-0-224_BRANCH Branch
Time : Thu May 28 14:42:58 CST 2015</center>
</body>
</html>
* Connection #0 to host www.baidu.com left intact
">"开头的行是本机发出的信息,"<"开头的行则是对方发出的信息,包括了HTTP头,状态码等
上面向百度POST了一个请求,当然是乱来的,所以对方响应了一个302把目标指向一个错误页面。还可以发现POST请求默认使用的Content-Type是
application/x-www-form-urlencoded
如果我们使用POST来测试一些RESTful接口的话,必须手工指定Content-Type为application/json(假设一般接口都是用json形式接收参数),否则服务端接收到的数据会含有%开头的编码,可以使用 -H 来指定Content-Type这个HTTP头
curl -XPOST 'http://ip:port/api/resource' -d '{"name":"hi"}' -H 'Content-Type: application/json'







