时间: 2020-11-26|63次围观|0 条评论

开发中常见的调用http的工具除了PostMan外,最常用的就数Curl命令了。

官方文档有非常非常详尽的介绍:https://curl.haxx.se/docs/httpscripting.html

如http协议的相关用法:https://curl.haxx.se/docs/httpscripting.html#The_HTTP_Protocol

最简练的手册https://curl.haxx.se/docs/manual.html  (超级推荐看这个)

本文简单介绍其中常用的一小部分。

一、GET请求

如最基本的GET请求:

使用curl发送GET请求的格式为:curl protocol://address:port/url?args

例如:

 curl https://curl.haxx.se

当然如果请求后端的GET接口,也可以得到查询的数据信息。

如果有参数直接拼接在后面即可如:

curl ‘http://127.0.0.1:8080/login?name=admin&passwd=12345678’
 

二、POST请求

POST请求的格式:curl -d "args" protocol://address:port/url

带参数的例子:

curl -d "user=admin&passwd=12345678" http://127.0.0.1:8080/login

POST数组,比如后端参数为 String[] itemNames,如果想传入a,b,c,d四个元素,这么写:

curl -d 'itemNames=a&itemNames=b&itemNames=c&itemNames=d'  'http://127.0.0.1:8080/debug/xxxx/yyy'

 

三、多个请求一起发

3.1 多个url

也可以一行连发多个Get请求

curl http://url1.example.com http://url2.example.com

多个POST

curl --data name=curl http://url1.example.com http://url2.example.com

3.2 多个请求方法

先发HEAD请求然后发GET请求

curl -I http://example.com --next http://example.com

先发POST请求然后发GET请求

curl -d score=10 http://example.com/post.cgi --next http://example.com/results.html

4、表单格式

4.1 GET表单

<form method="GET" action="junk.cgi">
 <input type=text name="birthyear">
 <input type=submit name=press value="OK">
 </form>

对应的get请求

curl "http://www.hotmail.com/when/junk.cgi?birthyear=1905&press=OK"

4.2 POST表单

<form method="POST" action="junk.cgi">
 <input type=text name="birthyear">
 <input type=submit name=press value=" OK ">
 </form>

请求方式

 curl --data "birthyear=1905&press=%20OK%20"  http://www.example.com/when.cgi

使用URL编码

curl --data-urlencode "name=I am Daniel" http://www.example.com

4.3 文件上传

<form method="POST" enctype='multipart/form-data' action="upload.cgi">

 <input type=file name=upload>
 <input type=submit name=press value="OK">
</form>

对应命令:

curl --form upload=@localfilename --form press=OK [URL]

4.4 隐藏域

<form method="POST" action="foobar.cgi">

 <input type=text name="birthyear">
 <input type=hidden name="person" value="daniel">
 <input type=submit name="press" value="OK">
</form>

对应命令

curl --data "birthyear=1905&press=OK&person=daniel" [URL]

 

5、Cookies

基本用法

curl --cookie "name=Daniel" http://www.example.com

 

更多高级用法参见官方文档

https://curl.haxx.se/docs/httpscripting.html

https://curl.haxx.se/docs/

如果觉得本文对你有帮助,欢迎点赞评论,欢迎关注我,我将努力创作更多更好的文章。

原文链接:https://blog.csdn.net/w605283073/article/details/89528371

本站声明:网站内容来源于网络,如有侵权,请联系我们,我们将及时处理。

本博客所有文章如无特别注明均为原创。
复制或转载请以超链接形式注明转自起风了,原文地址《使用curl 命令模拟POST/GET请求的正确姿势
   

还没有人抢沙发呢~