使用curl

curl 是一种使用URL从服务器获取数据或者向服务器传输数据的工具。在做一些简单的请求测试的时候可以直接在命令行执行curl指令,而不用打开Postman之类的App,减少一些操作步骤。

curl支持的协议有很多,比如HTTPHTTPSWSWSS等,本文以HTTP协议的URL为例说明一些用法。

  1. 简单的GET请求:
shell 复制代码
$ curl http://localhost:8080/hello
hello world!
  1. 使用-X--request)指定请求方法:
shell 复制代码
$ curl -X POST localhost:8080/user/login

不使用-X默认是GET请求。

  1. 使用-i--include)将响应头中的数据打印出来:
shell 复制代码
$ curl -i -X GET "localhost:8080/echo?name=孙悟空&address=花果山水帘洞"
HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
Date: Thu, 14 Dec 2023 13:32:03 GMT
Content-Length: 60
​
{"data":{"name":"孙悟空","address":"花果山水帘洞"}}                                         
  1. 使用-v--verbose)打印出一些冗长的信息,调试的时候可以使用:
shell 复制代码
curl -v localhost:8080/孙悟空/987fbc97-4bed-5078-9f07-9141ba07c9f3
*   Trying 127.0.0.1:8080...
* Connected to localhost (127.0.0.1) port 8080 (#0)
> GET /%e5%ad%99%e6%82%9f%e7%a9%ba/987fbc97-4bed-5078-9f07-9141ba07c9f3 HTTP/1.1
> Host: localhost:8080
> User-Agent: curl/7.88.1
> Accept: */*
> 
< HTTP/1.1 200 OK
< Content-Type: application/json; charset=utf-8
< Date: Fri, 15 Dec 2023 03:13:17 GMT
< Content-Length: 73
< 
* Connection #0 to host localhost left intact
{"data":{"id":"987fbc97-4bed-5078-9f07-9141ba07c9f3","name":"孙悟空"}}
  1. 使用-d--data)在POST请求中携带数据:
shell 复制代码
$ curl -X POST -d '{"name": "孙悟空", "address": "花果山水帘洞"}' localhost:8080/echo \
>  -H "Content-Type:application/json"
{"data":{"name":"孙悟空","address":"花果山水帘洞"}}

或者:

shell 复制代码
$ curl -X POST -d "name=孙悟空&address=花果山水帘洞" localhost:8080/echo
{"data":{"name":"孙悟空","address":"花果山水帘洞"}}

因为GET的数据是在url中携带的,所以直接这样请求:

shell 复制代码
$ curl -i -X GET "localhost:8080/echo?name=孙悟空&address=花果山水帘洞"
  1. 使用-H--header) 设置请求头:
shell 复制代码
$ curl -X POST -d '{"name": "孙悟空", "address": "花果山水帘洞"}' localhost:8080/echo \
>  -H "Content-Type:application/json"
{"data":{"name":"孙悟空","address":"花果山水帘洞"}}
  1. -F--form)模拟用户按下提交按钮后填写的表单,使用-F后的Content-Typemultipart/form-data
shell 复制代码
$ curl -X POST localhost:8080/upload \
> -F "upload=@/Users/path/上传用的文件.txt"
1 files uploaded!
相关推荐
怎么没有名字注册了啊6 天前
解决Undefined symbol: _curl_easy_cleanup
c++·curl
请为小H留灯12 天前
网络连通性测试:3 种常用方法(Telnet、Ping、Curl)详解
网络·curl·telnet·网络测试
REDcker17 天前
curl开发者快速入门
linux·服务器·c++·c·curl·后端开发
REDcker17 天前
curl完整文档
c++·c·curl·服务端·后端开发
ymwlchina19 天前
网站维护必须掌握的curl命令的用法
curl
予枫的编程笔记22 天前
【Linux进阶篇】Linux网络配置+端口监听实战:ip/ss/iptables常用命令一次吃透
linux·iptables·网络配置·curl·端口监听·ping·ss命令
Wpa.wk1 个月前
curl-发送请求 和 tcpdump与wireshark的介绍
测试工具·wireshark·tcpdump·curl
云游云记1 个月前
php cURL 常用参数详解与实用指南
开发语言·php·curl
sxy_97611 个月前
AX86u官方固件温度监控(CPU,WIFI芯片)
python·docker·curl·nc·nas·温度·ax86u
码农爱学习1 个月前
curl使用读回调来分块上报文件
curl