Linux - 使用curl发起post请求

2023-05-06 03:54:28

 

开发人员可以使用cURL来测试API接口,查看响应头和发出HTTP请求。

在本文中,我们将解释如何使用cURL发出POST请求。HTTP POST方法用于将数据发送到远程服务器

发出POST请求

curl 发出POST请求的命令的一般形式如下:

curl -X POST [options] [URL]

该-X选项指定与远程服务器通信时将使用哪种HTTP请求方法。

请求主体的类型由其Content-Type标头指定。通常,POST请求是通过HTML表单发送的。发送到表单的数据通常以multipart/form-data或application/x-www-form-urlencoded内容类型进行编码。

要创建POST请求,请使用-F选项,然后使用key=value配对。下面的示例说明如何向具有“name”和“email”字段的表单发出POST请求:

curl -X POST -F name=Jason -F email=jason@example.com https://xxxxxx.com/contact.php

使用该-F选项时,curl使用 Content-Type 为“multipart/form-data”发送数据。

发出POST请求的另一种方法是使用-d选项。这导致curl使用application/x-www-form-urlencodedContent-Type发送数据。

curl -X POST -d name=Jason -d email=jason@example.com https://xxxxxx.com/contact.php

如果-d多次使用该选项,则可以使用&符号合并数据:

curl -X POST -d name=Jason&email=jason@example.com https://xxxxxx.com/contact.php

指定Content-Type

要设置特定的标题或Content-Type,请使用-H选项。以下命令将POST请求类型设置为,application/json并发送JSON对象:

curl -X POST -H "Content-Type: application/json" -d {"name": "Jason", "email": "jason@example.com"} https://xxxx/contact

文件上传

要使用curl来上传文件,只需在文件位置之前添加 at 符号。该文件可以是任何支持的类型。

curl -X POST -F image=@/home/user/Pictures/wallpaper.jpg http://example.com/upload

设置代理

1、curl命令设置http代理:

将请求代理到 113.185.19.192 服务器的 80 端口

# 指定http代理IP和端口 curl -x 113.185.xx.xx:80 http://xxxxxx.com/test.php curl --proxy 113.185.xx.xx:80 http://xxxxxx.com/test.php #指定为http代理 curl -x http_proxy://113.185.xx.xx:80 http://xxxxxx.com/test.php #指定为https代理 curl -x HTTPS_PROXY://113.185.xx.xx:80 http://xxxxxx.com/test.php #指定代理用户名和密码,basic认证方式 curl -x root:123456@113.185.xxx.xx:80 http://xxxxxx.com/test.php curl -x 113.185.xx.xx:80 -U root:123456 http://xxxxxx.com/test.php curl -x 113.185.xx.xx:80 --proxy-user root:123456 http://xxxxxx.com/test.php #指定代理用户名和密码,ntlm认证方式 curl -x 113.185.xx.xx:80 -U root:123456 --proxy-ntlm http://xxxxxx.com/test.php #指定代理协议、用户名和密码,basic认证方式 curl -x http_proxy://root:123456@113.185.xx.xx:80 http://xxxxxx.com/test.php

2、curl命令设置socks代理:

#使用socks4代理,无需认证方式 curl --socks4 122.192.xx.xx:7280 http://xxxxxx.com/test.php curl -x socks4://122.192.xx.xx:7280 http://xxxxxx.com/test.php #使用socks4a代理,无需认证方式 curl --socks4a 122.192.xx.xx:7280 http://xxxxxx.com/test.php curl -x socks4a://122.192.xx.xx:7280 http://xxxxxx.com/test.php #使用socks5代理,basic认证方式 curl --socks5 122.192.xx.xx:7280 -U root:123456 http://xxxxxx.com/test.php curl -x socks5://root:123456@122.192.xx.xx:7280 http://xxxxxx.com/test.php #使用socks5代理,basic认证方式,ntlm认证方式 curl -x socks5://root:123456@122.192.xx.xx:7280 --proxy-ntlm http://xxxxxx.com/test.php

进行接口测试

curl -X POST -H "Content-Type: application/json" -d {"instid": "ivMaUO6fBSQU5TIgITqv1clITO2kMDpD", "status": "Y"} http://10.66.xx.xx:6819/uip/ctghttpServer/callback


以上就是关于《Linux - 使用curl发起post请求》的全部内容,本文网址:https://www.7ca.cn/baike/22807.shtml,如对您有帮助可以分享给好友,谢谢。
标签:
声明