【http】还在用postman?curl它不香吗

curl是什么?c可以看作是client,url(Uniform Resource Locator)是统一资源定位符。curl可以为指定的url执行网络传输,在shell和脚本中它是如此便捷、强大、可靠。

curl支持n多协议(ftp、smtp等等),本文只讨论有关http基于命令行的相关话题,使用curl完全可以轻而易举地取代postman之流的图形界面工具。下面看下使用curl发起http请求。

1.发起http get请求

curl http://localhost:8080/demo
2.使用-v 详细显示请求响应相关信息
curl -v http://localhost:8080/demo
3.使用-G -d 发起get请求并发送数据
curl -G -d "hello" -v http://1ocalhost:8080/demo
4.使用-I 发起head请求
curl -I http://localhost:8080/demo
5.使用-i  响应包含头部信息
curl -i http://localhost:8080/demo
----
以上是基本的get请求示例,下面看下使用curl发起需要登录认证的请求。
6.使用-u 提供用户名密码
curl -u 'admin:admin' http://localhost:9002/actuator
7.curl自动识别用户名密码
curl http://admin:admin@localhost:9002/actuator
8.使用-u 仅输入用户名 会提示密码输入
curl -u 'admin' http://localhost:9002/actuator
9.使用-c 保存服务端响应的cookie
curl -u 'admin:admin' -c cookie.txt http://localhost:9002/actuator
10.使用-b 携带cookie信息发起http请求
curl -b cookie.txt http://localhost:9002/actuator
----
下面看下使用curl发送post请求。
11.使用-d 发送http post请求数据 -H指定head line头信息
curl -d "{'name':'star','age':20}" -H  "Content-type:application/json"  http://localhost:8080/demo/post
12.使用@引用文件 包含请求数据的文件
curl -d @post_data -H "Content-type:application/json" http://localhost:8080/demo/post
13.使用-F选项 post上传文件
curl -F '[email protected]'http://localhost:8080/demo/file
14.使用--data-urlencode编码 提交数据
curl --data-urlencode 'name=码农小麦' -v http://localhost:8080/demo/urlencode
15.使用-d 提交请求数据
curl -d 'name=码农小麦' -d 'content=欢迎来撩' -v http://localhost:8080/demo/post
curl -d 'name=码农小麦&content=欢迎来撩' -v http://localhost:8080/demo/post
以上就是curl常见的命令行使用示例,完全可以应对日常的开发测试场景,以及脚本相关http请求功能实现。更多使用方法参见curl --help。


猜你喜欢

转载自blog.51cto.com/15060464/2638260