简单介绍shell中的curl网络请求的实现

本文详细介绍如何在shell中使用curl进行网络请求,包括查看网页源码、获取头信息、发送不同类型的请求,并探讨其在自动化脚本中的应用。

导读    本文主要介绍了shell中的curl网络请求的实现,文中通过示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
shell中的curl网络请求的实现

curl 是利用URL语法在命令行下工作的文件传输工具,1997年首次发行,支持文件上传和下载,结合shell脚本体验更棒。但按照传统习惯称 curl 为下载工具。

curl 支持的通信协议有 有FTP、FTPS、HTTP、HTTPS、TFTP、SFTP 等等,支持的平台有 Linux、MacOSX、Darwin、Windows、DOS、FreeBSD等等。

一、curl的作用:
1、查看网页源码
denglibingdeMacBook-Pro-4: curl www.baidu.com
 
< !DOCTYPE html>
< !--STATUS OK-->< html> < meta content=always name=referrer>< link rel=stylesheet type=text/css href=http://s1.bdstatic.com/r/www/cache/bdorz/baidu.min.css>< title>百度一下,你就知道 < body link=#0000cc> < div id=wrapper> < div id=head> < div class=head_wrapper> < div class=s_form> < div class=s_form_wrapper> < div id=lg> < img hidefocus=true src= //www.baidu.com/img/bd_logo1.png width=270 height=129>  < form id=form name=f action=//www.baidu.com/s class=fm> < input type=hidden name=bdorz_come value=1> < input type=hidden name=ie value=utf-8> < input type=hidden name=f value=8> < input type=hidden name=rsv_bp value=1> < input type=hidden name=rsv_idx value=1> < input type=hidden name=tn value=baidu>< span class="bg s_ipt_wr">< input id=kw name=wd class=s_ipt value maxlength=255 autocomplete=off autofocus>< span class="bg s_btn_wr">< input type=submit id=su value=百度一下 class="bg s_btn">    
 < a href=http://news.baidu.com name=tj_trnews class=mnav>新闻 < a href=http://www.hao123.com name=tj_trhao123 class=mnav>hao123  < a href=http://map.baidu.com name=tj_trmap class=mnav>地图 < a href=http://v.baidu.com name=tj_trvideo class=mnav>视频 < a href=http://tieba.baidu.com name=tj_trtieba class=mnav>贴吧 < noscript> < a href=http://www.baidu.com/bdorz/login.gif?login&tpl=mn&u=http%3A%2F%2Fwww.baidu.com%2f%3fbdorz_come%3d1 name=tj_login class=lb>登录  < script>document.write('< a href="http://www.baidu.com/bdorz/login.gif?login&tpl=mn&u='+ encodeURIComponent(window.location.href+ (window.location.search === " rel="external nofollow" " ? "?" : "&")+ "bdorz_come=1")+ '" name="tj_login" class="lb">登录'); < a href=//www.baidu.com/more/ name=tj_briicon class=bri style="display: block;">更多产品 
   < div id=ftCon> < div id=ftConw> 
 < a href=http://home.baidu.com>关于百度 < a href=http://ir.baidu.com>About Baidu 

 < p id=cp>©2017 Baidu < a href=http://www.baidu.com/duty/>使用百度前必读  < a href=http://jianyi.baidu.com/ class=cp-feedback>意见反馈 京ICP证030173号  < img src=//www.baidu.com/img/gs.gif>      
 
// 保存整个网页,使用 -o 处理
denglibingdeMacBook-Pro-4: curl -o baidu www.baidu.com
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100  2381  100  2381    0     0  77899      0 --:--:-- --:--:-- --:--:-- 79366
2、查看头信息
denglibingdeMacBook-Pro-4: denglibing$ curl -i www.baidu.com
HTTP/1.1 200 OK
Server: bfe/1.0.8.18
Date: Mon, 03 Jul 2017 09:12:17 GMT
Content-Type: text/html
Content-Length: 2381
Last-Modified: Mon, 23 Jan 2017 13:28:11 GMT
Connection: Keep-Alive
ETag: "588604eb-94d"
Cache-Control: private, no-cache, no-store, proxy-revalidate, no-transform
Pragma: no-cache
Set-Cookie: BDORZ=27315; max-age=86400; domain=.baidu.com; path=/
Accept-Ranges: bytes
...
...
...
3、发送网络请求信息
GET方式请求:

curl example.com/form.cgi?data=xxx  如果这里的URL指向的是一个文件或者一幅图都可以直接下载到本地www.linuxprobe.com
POST方式请求:

//数据和网址分开,需要使用 '--data' 或者 '-d' 参数; curl默认使用GET,使用 '-X' 参数可以支持其他动词, 更多的参数使用 'man curl' 查看
$ curl -X POST --data "data=xxx" example.com/form.cgi
 
// '--user-agent' 字段,表表面客户端的设备信息:
$ curl --user-agent "Mozilla/5.0 (iPhone; CPU iPhone OS 10_3_2 like Mac OS X) AppleWebKit/603.2.4 (KHTML, like Gecko) Mobile/14F89/mideaConnect MissonWebKit/4021/zh-Hans (AppStore) (4347701760)" http://www.example.com
 
//使用 '--cookie' 参数,可以让curl发送cookie
$ curl --cookie "name=xxx" www.example.com
 
//添加头信息,自行增加一个头信息。'--header' 或者 '-H' 参数就可以起到这个作用
$ curl --header "Content-Type:application/json" http://example.com
 
 
//提交文件作为请求信息 使用 '@文件名' 请求
$ curl -X POST -H "Content-Type: text/xml" -d @denglibing.txt http://example.com
 
//denglibing.txt:
11622695,D58C6A25-C683-47D6-A18C-B7741284F632
二、实例
denglibingdeMacBook-Pro-4:~ denglibing$ curl https://api.github.com/users
[
  {
    "login": "mojombo",
    "id": 1,
    "avatar_url": "https://avatars3.githubusercontent.com/u/1?v=3",
    "gravatar_id": "",
    "url": "https://api.github.com/users/mojombo",
    "html_url": "https://github.com/mojombo",
    "followers_url": "https://api.github.com/users/mojombo/followers",
    "following_url": "https://api.github.com/users/mojombo/following{/other_user}",
    "gists_url": "https://api.github.com/users/mojombo/gists{/gist_id}",
    "starred_url": "https://api.github.com/users/mojombo/starred{/owner}{/repo}",
    "subscriptions_url": "https://api.github.com/users/mojombo/subscriptions",
    "organizations_url": "https://api.github.com/users/mojombo/orgs",
    "repos_url": "https://api.github.com/users/mojombo/repos",
    "events_url": "https://api.github.com/users/mojombo/events{/privacy}",
    "received_events_url": "https://api.github.com/users/mojombo/received_events",
    "type": "User",
    "site_admin": false
  }
]
当然,既然这些请求是在命令行中执行,完全可以写成shell脚本,来处理一系列的工作,比如多个请求,而shell脚本在Mac中,可以使用定时任务触发,进而完成一系列的自动化工作。

<think> 我们正在讨论的是使用shell脚本实现curl发送POST请求的方法。根据用户的问题,他想要查找使用shell脚本实现curl post请求的示例。我们可以参考站内引用中提供的几个示例。 回顾引用: 引用[2]提供了一个基本的curl发送POST请求的例子: ```shell curl -X POST -H "Content-Type: application/json" -H "referer:http://localhost" http://localhost:8080/test/file/import -d '{"param":"20210608"}' ``` 引用[5]也有类似的例子: ```shell curl -H "Content-Type: application/json" -X POST -d '{"username":"jack","age":10}' http://example.com/api/user ``` 因此,我们可以总结出使用curl发送POST请求的基本格式: ```shell curl [选项] [URL] 其中,常用选项包括: -X POST 指定请求方法为POST -H "Header: value" 设置请求头,例如设置内容类型为JSON:-H "Content-Type: application/json" -d 'data' 指定要发送的数据,数据可以是字符串,也可以是JSON格式 如果发送JSON数据,通常需要设置Content-Type为application/json。 ``` 现在,我们可以编写一个shell脚本,使用curl发送POST请求。以下是一个示例脚本,该脚本将向指定的URL发送一个JSON格式的POST请求。 ### Shell脚本使用curl发送POST请求的示例 以下脚本(`post_request.sh`)演示了如何使用curl发送POST请求。脚本接受三个参数:URL、JSON数据字符串和可选的Referer头(如果不提供Referer,则默认不设置)。 ```bash #!/bin/bash # 检查参数数量 if [ $# -lt 2 ]; then echo "用法: $0 <URL> <JSON数据> [Referer]" echo "示例: $0 'http://example.com/api' '{\"username\":\"jack\",\"age\":10}' 'http://localhost'" exit 1 fi URL=$1 JSON_DATA=$2 REFERER=$3 # 设置默认的Referer,如果未提供第三个参数,则不设置Referer头 if [ -z "$REFERER" ]; then # 发送不带Referer头的请求 curl -X POST \ -H "Content-Type: application/json" \ -d "$JSON_DATA" \ "$URL" else # 发送带Referer头的请求 curl -X POST \ -H "Content-Type: application/json" \ -H "referer:$REFERER" \ -d "$JSON_DATA" \ "$URL" fi # 检查curl命令的退出状态 if [ $? -eq 0 ]; then echo "请求发送成功!" else echo "请求发送失败!" exit 1 fi ``` #### 脚本说明 1. **参数检查**:脚本要求至少两个参数(URL和JSON数据)。第三个参数Referer是可选的。 2. **设置请求头**:对于JSON数据,必须设置`Content-Type: application/json`。如果提供了Referer参数,则添加`referer`头[^2]。 3. **发送请求**:使用`curl -X POST`发送POST请求,`-d`参数后面跟上JSON数据字符串。 4. **错误处理**:检查curl命令的退出状态(`$?`),如果为0表示成功,否则失败。 #### 使用示例 1. 保存脚本为`post_request.sh`。 2. 赋予执行权限:`chmod +x post_request.sh`。 3. 执行脚本(不带Referer): ```bash ./post_request.sh 'http://example.com/api' '{"username":"jack","age":10}' ``` 4. 执行脚本(带Referer): ```bash ./post_request.sh 'http://example.com/api' '{"username":"jack","age":10}' 'http://localhost' ``` #### 注意事项 - **JSON数据格式**:在命令行中传递JSON数据时,注意引号的处理。在双引号内部使用JSON数据,因此JSON内的双引号需要用反斜杠转义(例如`{\"key\":\"value\"}`)。也可以使用单引号包裹JSON字符串,这样内部的双引号就不需要转义,但是在上面的脚本中,我们将JSON数据作为第二个参数传递,在调用脚本时用户输入的JSON字符串需要按照shell的规则进行转义。上面的示例调用中,我们使用了单引号包裹整个JSON字符串,这样内部的双引号就不需要转义(因为shell会将其视为字符串),但是注意在脚本内部,我们直接将参数传递给了curl,所以用户需要确保传递的JSON是有效的。 - **空格处理**:如果URL或JSON数据包含空格,务必用引号包裹参数。 - **安全性**:此脚本未对输入进行安全验证,实际应用中可能需要增强(如检查URL格式)。 通过这种方法,您可以轻松地用shell脚本发送POST请求,并集成到自动化任务中。 §§相关问题§§ 1. 如何在shell脚本中处理curl请求的响应? 2. shell脚本如何发送带认证头(如Bearer Token)的POST请求? 3. 如何使用shell脚本发送multipart/form-data类型的POST请求(例如文件上传)? </think> ### Shell脚本实现CURL POST请求的方法详解 在Shell脚本中使用`curl`发送POST请求是自动化HTTP交互的核心技术,尤其在API调用、数据提交和微服务通信等场景中广泛应用。根据您的需求,我将详细介绍实现方法并提供完整示例。 --- ### 一、CURL POST请求基础语法 `curl`发送POST请求的核心参数: ```bash curl -X POST \ # 指定请求方法 -H "Header:值" \ # 设置请求头 -d '数据内容' \ # 设置请求体 URL地址 ``` **关键参数说明**: - `-X POST`:显式声明POST方法(可省略,`-d`默认触发POST) - `-H`:设置请求头(如`Content-Type`) - `-d`:发送表单数据(默认`application/x-www-form-urlencoded`) - `--data-binary`:发送二进制数据(不进行编码转换) - `-F`:发送multipart/form-data(文件上传) --- ### 二、JSON格式POST请求示例 这是最常见的API交互方式,需要设置正确的Content-Type(参考引用[2][5]): ```bash #!/bin/bash # 目标API地址 API_URL="http://example.com/api/user" # JSON请求体(注意单引号避免变量展开) JSON_DATA='{"username": "jack", "age": 25, "active": true}' # 发送请求 curl -X POST \ -H "Content-Type: application/json" \ -H "Authorization: Bearer token123" \ # 认证头 -d "$JSON_DATA" \ "$API_URL" ``` **执行结果处理**: ```bash response=$(curl -s -X POST ...) # -s静默模式 echo "响应状态码: $?" echo "响应内容: $response" ``` --- ### 三、表单数据POST请求 适用于传统网页表单提交(默认`application/x-www-form-urlencoded`): ```bash curl -X POST \ -d "username=jack&password=secret" \ http://example.com/login ``` **多字段简化写法**: ```bash curl -d "param1=value1" -d "param2=value2" URL ``` --- ### 四、文件上传(multipart/form-data) 通过`-F`参数实现文件传输(引用[4]服务端脚本可处理此类请求): ```bash curl -X POST \ -F "file=@/path/to/file.txt;type=text/plain" \ -F "description=配置文件" \ http://example.com/upload ``` --- ### 五、完整脚本示例 ```bash #!/bin/bash # post_request.sh - 带错误处理的POST请求脚本 if [ $# -ne 1 ]; then echo "用法: $0 <API_URL>" exit 1 fi API_URL=$1 TIMESTAMP=$(date +%s) JSON_PAYLOAD=$(cat <<EOF { "request_id": "req_$TIMESTAMP", "data": {"action": "query", "params": {"limit": 10}} } EOF ) # 发送请求并捕获响应 response=$(curl -sS -X POST \ -w "\nHTTP状态码: %{http_code}" \ -H "Content-Type: application/json" \ -H "X-Request-ID: $TIMESTAMP" \ -d "$JSON_PAYLOAD" \ "$API_URL" 2>&1) # 解析结果 if [ $? -eq 0 ]; then echo "请求成功!" echo "响应内容:" echo "$response" | sed '$d' # 移除状态行 http_code=$(echo "$response" | tail -1 | awk '{print $NF}') echo "HTTP状态码: $http_code" else echo "请求失败: $response" exit 2 fi ``` **使用方式**: ```bash ./post_request.sh https://api.example.com/endpoint ``` --- ### 六、调试与错误处理技巧 1. **详细日志**:添加`-v`参数查看完整HTTP交互 ```bash curl -v -X POST ... ``` 2. **超时控制**:避免脚本挂起 ```bash curl --max-time 30 ... # 30秒超时 ``` 3. **重试机制**:对临时故障自动重试 ```bash curl --retry 3 --retry-delay 5 ... ``` 4. **证书跳过**:开发环境绕过HTTPS验证(生产环境禁用) ```bash curl -k ... # 跳过SSL验证 ``` --- ### 常见问题解答 **Q1 如何处理JSON中的特殊字符?** ```bash # 使用jq生成JSON(推荐) JSON_DATA=$(jq -n --arg user "jack" '{username: $user}') # 或手动转义双引号 JSON_DATA='{\"name\": \"value\"}' ``` **Q2 如何发送数组类型JSON?** ```bash curl -X POST \ -H "Content-Type: application/json" \ -d '[1, 2, 3]' \ http://example.com/array ``` 通过掌握这些技术,您可以构建复杂的HTTP自动化工作流,如API测试、数据同步和微服务编排。建议结合引用[3]的libcurl文档深入了解底层原理。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值