无curl环境下,如何用wget自动编码参数发送URL编码POST请求?
用Wget或系统自带工具实现自动URL编码的POST请求
没问题!完全可以用wget或者Linux极简系统自带的其他工具,实现和curl --data-urlencode一样的自动URL编码+POST请求功能,下面给你几种靠谱的方案:
方案1:Wget + Shell内置printf编码
Wget本身没有像curl那样直接的自动URL编码选项,但我们可以用shell自带的printf %q先完成编码,再传给Wget的--post-data参数:
u="url=http://somewhere.net?param1=val1¶m2=val2" # 用printf编码,再把空格的转义替换成URL标准的+ encoded_u=$(printf "%q" "$u" | sed 's/\\ /+/g') # 发送POST请求 wget --post-data "$encoded_u" http://example.com
printf %q会把特殊字符转成shell安全的格式,基本符合URL编码要求;如果需要用%20代替空格,把sed命令改成s/\\ /%20/g即可。
方案2:Wget + Perl(更标准的URL编码)
如果需要严格符合RFC标准的URL编码(处理所有特殊字符),可以用几乎所有Linux系统都自带的Perl来完成编码:
u="url=http://somewhere.net?param1=val1¶m2=val2" # 借助Perl的URI::Escape模块完成标准编码 encoded_u=$(perl -MURI::Escape -e 'print uri_escape($ARGV[0])' "$u") # 发送POST请求 wget --post-data "$encoded_u" http://example.com
Perl的URI::Escape模块是标准库的一部分,能准确处理所有需要编码的字符,比printf的方法更可靠。
方案3:用Netcat(nc)手动构造请求(极端情况)
如果你的系统连Wget都没有(极少出现),可以用系统自带的nc(Netcat)手动构造HTTP请求,不过需要自己处理编码和HTTP头:
u="url=http://somewhere.net?param1=val1¶m2=val2" encoded_u=$(perl -MURI::Escape -e 'print uri_escape($ARGV[0])' "$u") # 构造完整的HTTP POST请求并发送 echo -e "POST / HTTP/1.1\r\nHost: example.com\r\nContent-Type: application/x-www-form-urlencoded\r\nContent-Length: ${#encoded_u}\r\n\r\n$encoded_u" | nc example.com 80
这个方法需要注意Content-Length的准确计算,以及HTTP头的格式(必须用\r\n换行),适合极端极简环境使用。
内容的提问来源于stack exchange,提问作者user4918296
相关产品推荐
相关产品推荐

