一、post
1、server
package main
import (
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
)
func main() {
//创建路由
server := http.NewServeMux()
server.HandleFunc("/login",login)
http.ListenAndServe(":2001",server)
}
func login(w http.ResponseWriter,r *http.Request) {
r.ParseForm()
bytes, err := ioutil.ReadAll(r.Body)
if err != nil {
log.Fatal(err)
}
r.Body.Close()
fmt.Println("Body:",string(bytes))
fmt.Printf("r=%+v\n",r)
fmt.Printf("r.Header=%+v\n",r.Header)
fmt.Printf("Content-Type=%+v\n",r.Header["Content-Type"])
fmt.Printf("r.Cookies()=%+v\n",r.Cookies())
if len(r.Form["username"]) > 0 {
username := r.Form["username"][0]
fmt.Println("username:",username)
}
if len(r.Form["password"]) > 0 {
password := r.Form["password"][0]
fmt.Println("password",password)
}
io.WriteString(w,"登录成功")
}
2、cilent
package main
import (
"bytes"
"fmt"
"io/ioutil"
"log"
"net/http"
"net/url"
)
func main() {
//自己搭建服务器
str := "http://127.0.0.1:2001/login"
param := url.Values{
"username" : {"大笨蛋"},
"password" : {"123456789@qq.com"},
}
bufferString := bytes.NewBufferString(param.Encode())
resp, err := http.Post(str, "application/x-www.form-urlencoded", bufferString)
if err != nil {
log.Fatal(err)
}
//关闭链接
defer resp.Body.Close()
if resp.StatusCode == 200 {
all, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Fatal(err)
}
fmt.Println(string(all))
}
fmt.Println("respone",resp)
fmt.Println("respone.Header",resp.Header)
fmt.Println("responre.Cookies",resp.Cookies())
}
|