golang get/post 请求样例
func demo02() {
url := "http://www.baidu.com"
username := "zhangsan"
password := "password"
loginRequest := LoginRequest{Username: username, Password: password}
postData, err := json.Marshal(loginRequest)
if err != nil {
fmt.Println("Parse json failed:", err)
return
}
fmt.Println("URL:>", url, "PostData:>", postData)
fmt.Println("loginRequest:", bytes.NewBuffer(postData))
reader := bytes.NewReader(postData)
request, err := http.NewRequest("POST", url, reader)
if err != nil {
fmt.Println("Http new Request object failed:", err)
return
}
request.Header.Set("Content-Type", "application/json;charset=UTF-8")
client := &http.Client{}
response, err := client.Do(request)
if err != nil {
fmt.Println("Execute post request failed:", err)
return
}
defer response.Body.Close()
fmt.Println("response status:", response.Status)
fmt.Println("response code:", response.StatusCode)
fmt.Println("response headers:", response.Header)
body, err := ioutil.ReadAll(response.Body)
if err != nil {
panic(err)
}
fmt.Println("response body:", string(body))
}
func demo01() {
response, err := http.Get("http://localhost:9000/http/user/?name=zhangsan")
if err != nil {
fmt.Println("err:", err)
return
}
b, err := ioutil.ReadAll(response.Body)
if err != nil {
fmt.Println("err:", err)
return
}
fmt.Println(string(b))
}