通过go语言实现http请求
客户端:
import (
"net/http"
"json"
"ioutil"
)
type Student struct{
id string
name string
}
type StudentReq struct{
id string
name string
}
func main() {
stu := Student{
id:"2ed4tg5fe35fgty3yy6uh",
name:"amber",
}
stu,err := json.Marshal(&stu)
reader := bytes.NewReader(stu)
request,err := http.NewRequest("POST", "http://192.168.1.12:8000/create", reader)
request.Header.Set("Content-Type", "application/json")
client:=&http.Client{}
response,err := client.Do(request)
defer response.Body.Close()
body,err := ioutil.ReadAll(response.Body)
fmt.Printf(string(body))
var stuReq StudentReq
err = json.UnMarshal(body, &stuReq)
fmt.Println(json.MarshalIndent(stuReq))
}
解析:
- stu,err := json.Marshal(&stu):将stu对象改为json格式
- reader := bytes.NewReader(stu):所以将json改为byte格式,作为body传给http请求
- request,err := http.NewRequest(“POST”, “http://192.168.1.12:8000/create”, reader):创建url
- response,err := client.Do(request):客户端发起请求,接收返回值
- body,err := ioutil.ReadAll(response.Body):读取body的值,类型是byte
- json.MarshalIndent(stuReq):修改json为标准格式