golang提交get,post请求(带参数)
package main
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"strings"
"unsafe"
)
func main() {
fmt.Println(getReq("zhangsan", "18"))
postReq("lisi", 19)
postReqJson1()
var j JsonPost
(*JsonPost).postReqJson2(&j) // 隐式调用
}
func getReq(name string, age string) string {
client := &http.Client{}
req, err := http.NewRequest("GET", "http://localhost:5000/get",
nil)
if err != nil {
panic(err)
}
query := req.URL.Query()
query.Add("name", name)
query.Add("age", age)
req.URL.RawQuery = query.Encode()
resp, err := client.Do(req)
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
panic(err)
}
resdata := string(body)
return resdata
}
func postReq(name string, age int) {
client := &http.Client{}
req, err := http.NewRequest("POST", "http://localhost:5000/post",
strings.NewReader(fmt.Sprintf("name=%s&age=%d", name, age)))
if err != nil {
panic(err)
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
resp, err := client.Do(req)
defer resp.Body.Close()
}
// 通过json提交post
func postReqJson1() {
url := "http://localhost:5000/post"
name := "wangwu"
age := 20
//json序列化
post := fmt.Sprintf("{\"name\":%s,\"age\":%d}", name, age)
fmt.Println(url, "post", post)
var jsonStr = []byte(post)
req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonStr))
req.Header.Set("Content-Type", "application/json")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
panic(err)
}
defer resp.Body.Close()
fmt.Println("status", resp.Status)
fmt.Println("response:", resp.Header)
body, _ := ioutil.ReadAll(resp.Body)
fmt.Println("response Body:", string(body))
}
type JsonPost struct {
}
func (jp *JsonPost) postReqJson2() {
post := make(map[string]interface{})
post["name"] = "王柳"
post["age"] = 21
bytesData, err := json.Marshal(post)
if err != nil {
fmt.Println(err.Error())
return
}
reader := bytes.NewReader(bytesData)
url := "http://localhost:5000/post"
request, err := http.NewRequest("POST", url, reader)
if err != nil {
fmt.Println(err.Error())
return
}
request.Header.Set("Content-Type", "application/json;charset=UTF-8")
client := http.Client{}
resp, err := client.Do(request)
if err != nil {
fmt.Println(err.Error())
return
}
respBytes, err := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Println(err.Error())
return
}
//byte数组直接转成string,优化内存
str := (*string)(unsafe.Pointer(&respBytes))
fmt.Println(*str)
}