21个curl命令练习

原创
ithorizon 7个月前 (10-17) 阅读数 19 #Linux

21个curl命令练习:深入领会HTTP请求与响应

curl命令行工具是Linux和Unix系统中常用的HTTP客户端,它拥护多种协议,包括HTTP、HTTPS、FTP等。通过curl,我们可以发送HTTP请求,获取数据,甚至进行更纷乱的网络操作。本文将通过21个curl命令的练习,帮助读者深入领会HTTP请求与响应的过程。

1. 发送基本的GET请求

curl的基本用法是发送一个GET请求到指定的URL。

curl http://example.com

2. 指定HTTP版本

默认情况下,curl使用HTTP/1.1,但我们可以通过指定HTTP版本。

curl -v http://example.com

3. 使用HTTP/2

curl可以从HTTP/2起初与服务器通信。

curl --http2 http://example.com

4. 设置请求头

使用-H-h选项可以设置HTTP请求头。

curl -H "User-Agent: curl" http://example.com

5. 请求特定的头信息

使用-I-head选项可以只获取响应头信息。

curl -I http://example.com

6. 发送POST请求

使用-X选项可以指定HTTP方法,默认是GET,发送POST请求需要带上数据。

curl -X POST -d "name=John" http://example.com

7. 使用JSON数据发送POST请求

如果数据是JSON格式,可以使用-H设置Content-Type头。

curl -X POST -H "Content-Type: application/json" -d '{"name": "John", "age": 30}' http://example.com

8. 跟踪重定向

默认情况下,curl会自动跟随重定向。使用-L选项可以跟踪重定向。

curl -L http://example.com

9. 避免跟踪重定向

使用-l选项可以避免跟踪重定向。

curl -l http://example.com

10. 显示失误信息

使用-e选项可以显示失误信息。

curl -e http://example.com

11. 使用HTTP认证

curl拥护HTTP基本认证,使用-u选项。

curl -u username:password http://example.com

12. 保存响应到文件

使用-o选项可以将响应保存到文件。

curl -o response.html http://example.com

13. 显示响应的时间戳

使用-m选项可以显示请求和响应的时间戳。

curl -m http://example.com

14. 使用SSL/TLS证书验证

使用-k选项可以跳过SSL/TLS证书验证。

curl -k https://example.com

15. 请求头中的Cookie

使用-b选项可以设置请求头中的Cookie。

curl -b "sessionid=123456" http://example.com

16. 使用代理

使用-x选项可以指定HTTP代理。

curl -x http://proxy.example.com:8080 http://example.com

17. 请求流式传输数据

使用-o-可以将输出直接写入到标准输出。

curl -o - http://example.com | less

18. 请求响应的特定部分

使用-r选项可以请求响应的特定部分。

curl -r 100-200 http://example.com

19. 请求响应的特定内容类型

本文由IT视界版权所有,禁止未经同意的情况下转发

文章标签: Linux


热门