URL编码
在web服务开发中,URL编码问题是绕不过的,本文简单总结一下。
由于一些特殊符号的存在,为了避免歧义,需要将这些特殊符号经过编码之后传递。
URL编码中最常见的就是加号(+)和空格( )了。
我们使用如下代码部署一个web服务
package main
import (
	"fmt"
	"log"
	"net/http"
)
func main() {
	http.HandleFunc("/", handler)
	log.Fatal(http.ListenAndServe("localhost:8080", nil))
}
func handler(w http.ResponseWriter, r *http.Request) {
	r.ParseForm()
	if r.Method == "GET" {
		for k, v := range r.Form {
			fmt.Printf("key:%s,value:%v\n", k, v)
		}
	} else {
		for k, v := range r.PostForm {
			fmt.Printf("key:%s,value:%v\n", k, v)
		}
	}
}
通过postman测试,得到的结论如下
GET请求
| 请求 | 实际请求 | 响应 | 
|---|---|---|
| a=hello world | a=hello%20world | a=hello world | 
| a=hello+world | a=hello+world | a=hello world | 
| a=hello%2Bworld | a=hello%2Bworld | a=hello+world | 
POST请求(Content-Type: application/x-www-form-urlencoded)
| 请求 | 实际请求 | 响应 | 
|---|---|---|
| a=hello world | a=hello%20world | a=hello world | 
| a=hello+world | a=hello%2Bworld | a=hello+world | 
| a=hello%2Bworld | a=hello%252Bworld | a=hello%2Bworld | 
参考资料
https://en.wikipedia.org/wiki/Percent-encoding
https://stackoverflow.com/questions/2678551/when-to-encode-space-to-plus-or-20
 
                    
                     
                    
                 
                    
                
 
 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号