美文网首页
shell脚本中对http的body参数做url-encode

shell脚本中对http的body参数做url-encode

作者: 猫尾草 | 来源:发表于2020-06-07 17:34 被阅读0次

    1. curl发送不含特殊字符的body参数

      假设现在有两个参数需要发送,不包含需要编码的字符,firstParam=asd,secondParam=qwe,则

    curl -X POST localhost:8080 -H "Content-Type: application/x-www-form-urlencoded" -d "firstParam=asd&secondParam=qwe"
    

    2. curl发送含特殊字符的body参数

      我们知道诸如加号+这样的符号,在作为http参数发送时需要做urlEncoder编码。如果参数中带有比如+这样的符号,我们有两种选择:

    2.1 手动编码参数

      两个参数firstParam=asd&,secondParam=qwe+,编码后firstParam=asd%26,secondParam=qwe%2B

    curl -X POST localhost:8080 -H "Content-Type: application/x-www-form-urlencoded" -d "firstParam=asd%26&secondParam=qwe%2B"
    

      当然这样手动对每个参数编码是很麻烦的。

    2.2 使用--data-urlencoder

      两个参数firstParam=asd+,secondParam=qwe+(这里特地加了&符号,是为了说明&符号也会被编码)。

    curl -X POST localhost:8080 -H "Content-Type: application/x-www-form-urlencoded" --data-urlencode "firstParam=asd&&secondParam=qwe+"
    

      执行报错Required String parameter 'secondParam' is not present,为什么呢?
      因为--data-urlencode并不能识别两个参数中间的&符号,把firstparam后面的字符串当作一个整体编码了,服务端接收到的firstParam是asd&&secondParam=qwe+,secondParam是null。
    修改一下:

    curl -X POST localhost:8080 -H "Content-Type: application/x-www-form-urlencoded" --data-urlencode "firstParam=asd&" --data-urlencode "secondParam=qwe+"
    

    3. 发送json参数

      使用json发送数据,:,这些符号中间不要有空格,有空格就会截断,导致报错Unexpected end-of-input within/between Object entries。此外"还要加上\

    curl -X POST localhost:8080/json -H "Content-Type: application/json" -d {\"firstParam\":\"asd\",\"secondParam\":\"qwe\"}
    

      因为http并不去解析json的内容,所以即使有上面类似的需要编码的字符也不需要编码处理,直接发送就行。

    curl -X POST localhost:8080/json -H "Content-Type: application/json" -d {\"firstParam\":\"asd&\",\"secondParam\":\"qwe+\"}
    

    相关文章

      网友评论

          本文标题:shell脚本中对http的body参数做url-encode

          本文链接:https://www.haomeiwen.com/subject/ooartktx.html