前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >如何对curl命令的数据进行url编码

如何对curl命令的数据进行url编码

作者头像
程序熵
发布2024-01-11 14:05:37
1760
发布2024-01-11 14:05:37
举报
文章被收录于专栏:技术汇技术汇

问:

我正在尝试编写一个用于测试的 bash 脚本,该脚本接受一个参数并通过 curl 将其发送到网站。我需要对值进行 url 编码,以确保特殊字符得到正确处理。最好的方法是什么?

这是我到目前为止的基本脚本:

代码语言:javascript
复制
#!/bin/bash
host=${1:?'bad host'}
value=$2
shift
shift
curl -v -d "param=${value}" http://${host}/somepath $@

答:

使用 curl --data-urlencode ;curl 的手册写到:

This posts data, similar to the other --data options with the exception that this performs URL-encoding. To be CGI-compliant, the <data> part should begin with a name followed by a separator and a content specification.

示例用法

代码语言:javascript
复制
curl \
    --data-urlencode "paramName=value" \
    --data-urlencode "secondParam=value2" \
    http://example.com

这需要 curl 7.18.0 或更新版本。使用 curl -V 来检查你的版本。

提问者的脚本可以改写为

代码语言:javascript
复制
#!/bin/bash

host=${1:?'bad host'}
value=$2
shift
shift
curl -v --data-urlencode "param=${value}" http://${host}/somepath $@

将脚本保存为 curl-test.sh 文件,在一个窗口使用 tcpdump 对上网的网口开启过滤抓包,在另一个窗口执行命令 bash curl-test.sh example.com "ABC efg" 进行测试,抓包截图如下:

可以发现参数 "ABC efg" 被编码成为 ABC%20efg,即字符空格被编码为 %20。

类似地,# $ : ; , ?等特殊字符都有其对应的 URL 编码。


参考文档:

  • stackoverflow question 296536
  • https://manpages.org/curl
本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2024-01-07,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 程序熵 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档