zl程序教程

您现在的位置是:首页 >  系统

当前栏目

linux curl发起GET / POST及表单请求;同时发送多个请求;携带cookie示例

LinuxCookie 示例 请求 多个 发送 get 表单
2023-09-14 09:01:51 时间

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

官方文档有非常非常详尽的介绍:curl - The Art Of Scripting HTTP Requests Using Curl

如http协议的相关用法:curl - The Art Of Scripting HTTP Requests Using Curl

最简练的手册:curl - Tutorial (超级推荐看这个)

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

一、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表单

对应的get请求

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

4.2 POST表单

请求方式

 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 文件上传

对应命令:

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

4.4 隐藏域

对应命令

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

5、Cookies

基本用法

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

参考链接:

curl - The Art Of Scripting HTTP Requests Using Curl

curl - Documentation Overview

使用curl 命令模拟POST/GET请求的正确姿势