Linux curl 中get和post的用法详解

xiaoxiao2021-02-27  126

curl是个什么东西呢?

我们在Linux中输入:man curl(linux命令不熟悉的话找男人man),可以看到如下描述:

DESCRIPTION curl is a tool to transfer data from or to a server, using one of the supported protocols (HTTP, HTTPS, FTP, FTPS, SCP, SFTP, TFTP, DICT, TELNET, LDAP or FILE). The command is designed to work without user interaction. curl offers a busload of useful tricks like proxy support, user authentication, FTP upload, HTTP post, SSL connections, cookies, file transfer resume and more. As you will see below, the numberof features will make your head spin! curl is powered by libcurl for all transfer-related features. See libcurl(3) for details.

上面的意思是:

curl支持的协议包括:HTTP、HTTPS、FTP、FTPS、SCP、SFTP、TFTP、DICT、TELNET、LDAP或FILE。它是一个能够传输数据到服务器或者拉取服务器数据的工具。该命令的设计用于无用户交互的场景。

curl提供了很多有用的技巧:比如支持代理、用户身份验证、FTP上传、HTTP post请求、SSL连接、cookies、文件传输等功能。curl需要libcurl支持。

简单的说,

在我们日常中经常在部署完一台服务器时,如果需要判断该台服务器是否可以正常工作,除了我们利用netstat –tlunp去确定端口号是否开启,我们还可以通过curlhttp://你的服务器地址 来对服务器进行类似浏览器的请求访问,当然curl也可以用于对接口的请求等等。具体curl的用法后面再讲。

 curl的常见用法

1、get请求数据

如果是在linux中执行

curl http://www.baidu.com?name=tim&sex=boy&num=120(错误

因为&在linux下被当做守护进程使用。(注意:Windows下get后跟多个参数会有问题)

curl http://www.baidu.com?name=tim\&sex=boy\&num=120(正确,不推荐)

推荐写法:

curl http://www.baidu.com?name=tim&sex=boy&num=120(正确,推荐)

(这里双引号也可以换成单引号)

这样服务端就可以正确接收发送过来的参数值。

2、post请求数据

curl –d  “name=tim&sex=boy”http://www.baidu.com (正确

服务端可以通过接收post请求过来的参数,获取name和sex的值。

curl --data-urlencode  “name=tim&sex=boy” http://www.baidu.com  (错误)

服务端只能获取到参数name的值为tim&sex=boy,丢失了参数sex的值。

推荐正确写法:

curl -k --data-urlencode “name=tim” --data-urlencode“sex=boy” https://www.baidu.com (正确

这里对每个参数都通过--data-urlencode进行编码,则服务端可以正确接收传递的参数。(这里-k 是针对https报错的处理)。

补充知识点:

wget常用来下载文件,加-c选项可以支持断点续传,curl常用来跟网站的API接口交互。
转载请注明原文地址: https://www.6miu.com/read-13248.html

最新回复(0)