如何为 curl 命令对数据进行 urlencode? [英] How to urlencode data for curl command?

查看:83
本文介绍了如何为 curl 命令对数据进行 urlencode?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

这是我目前的基本脚本:

#!/bin/bash主机=${1:?'坏主机'}价值=$2转移转移curl -v -d "param=${value}" http://${host}/somepath $@

解决方案

Use curl --data-urlencode;来自 man curl:

<块引用>

这会发布数据,类似于其他 --data 选项,不同之处在于它执行 URL 编码.为了符合 CGI, 部分应以名称开头,后跟分隔符和内容规范.

示例用法:

curl --data-urlencode "paramName=value" --data-urlencode "secondParam=value" http://example.com

有关详细信息,请参阅手册页.>

这需要 curl 7.18.0 或更新版本(2008 年 1 月发布).使用 curl -V 检查您的版本.

您也可以对查询字符串进行编码:

curl -G --data-urlencode "p1=value 1" --data-urlencode "p2=value 2" http://example.com# http://example.com?p1=value%201&p2=value%202

I am trying to write a bash script for testing that takes a parameter and sends it through curl to web site. I need to url encode the value to make sure that special characters are processed properly. What is the best way to do this?

Here is my basic script so far:

#!/bin/bash
host=${1:?'bad host'}
value=$2
shift
shift
curl -v -d "param=${value}" http://${host}/somepath $@

解决方案

Use curl --data-urlencode; from man 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.

Example usage:

curl 
    --data-urlencode "paramName=value" 
    --data-urlencode "secondParam=value" 
    http://example.com

See the man page for more info.

This requires curl 7.18.0 or newer (released January 2008). Use curl -V to check which version you have.

You can as well encode the query string:

curl -G 
    --data-urlencode "p1=value 1" 
    --data-urlencode "p2=value 2" 
    http://example.com
    # http://example.com?p1=value%201&p2=value%202

这篇关于如何为 curl 命令对数据进行 urlencode?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆