Go入门笔记-24 Post数据

方式1:

package main

import (
	"fmt"
	"net/http"
	"net/url"
)

func main() {
	data := make(url.Values)
	data["key"] = []string{"this is key"}
	data["value"] = []string{"this is value"}
	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")
}

方式2:

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.")
}

服务端:

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
	}
}  

以上代码转自:

http://blog.csdn.net/gophers/article/details/22870185

测试结果

 

不同代码编译成的大小不一样,如果考虑大小使用方式2

 

 

 

  

  

posted @ 2021-08-22 12:30  zhaogaojian  阅读(108)  评论(0编辑  收藏  举报