先写一个可以接收post请求的服务器:
package main import ( "fmt" "net/http" ) func main() { http.HandleFunc("/postpage",func(w http.ResponseWriter,r *http.Request) { //接受post请求,然后打印表单中key和value字段的值 if r.Method == "POST" { var ( key string = r.PostFormValue("key") value string = r.PostFormValue("value") ) fmt.Printf("key is : %s\n",key) fmt.Printf("value is: %s\n",value) } }) err := http.ListenAndServe(":80",nil) if err != nil { fmt.Println(err.Error()) return } }
然后我们使用net/http包来发送post请求:
package main import ( "fmt" "net/http" "net/url" ) func main() { //这里添加post的body内容 data := make(url.Values) data["key"] = []string{"this is key"} data["value"] = []string{"this is value"} //把post表单发送给目标服务器 res,err := http.PostForm("http://127.0.0.1/postpage",data) if err != nil { fmt.Println(err.Error()) return } defer res.Body.Close() fmt.Println("post send success") }
如果你不想用现成的包,那么下面这段代码就是直接通过HTTP协议实现post请求,运行效果和上面这段代码一样:
package main import ( "fmt" "net" ) func main() { //因为post方法属于HTTP协议,HTTP协议以TCP为基础,所以先建立一个 //TCP连接,通过这个TCP连接来发送我们的post请求 conn,err := net.Dial("tcp","127.0.0.1:80") if err != nil { fmt.Println(err.Error()) return } defer conn.Close() //构造post请求 var post string post += "POST /postpage HTTP/1.1\r\n" post += "Content-Type: application/x-www-form-urlencoded\r\n" post += "Content-Length: 37\r\n" post += "Connection: keep-alive\r\n" post += "Accept-Language: zh-CN,zh;q=0.8,en;q=0.6\r\n" post += "\r\n" post += "key=this is key&value=this is value\r\n" if _,err := conn.Write([]byte(post)); err != nil { fmt.Println(err.Error()) return } fmt.Println("post send success.") }
@H_301_39@如果转载请注明出处:http://blog.csdn.net/gophers/article/details/22870185