go语言实现http请求

通过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))
}

解析:

  1. stu,err := json.Marshal(&stu):将stu对象改为json格式
  2. reader := bytes.NewReader(stu):所以将json改为byte格式,作为body传给http请求
  3. request,err := http.NewRequest(“POST”, “http://192.168.1.12:8000/create”, reader):创建url
  4. response,err := client.Do(request):客户端发起请求,接收返回值
  5. body,err := ioutil.ReadAll(response.Body):读取body的值,类型是byte
  6. json.MarshalIndent(stuReq):修改json为标准格式
发布了171 篇原创文章 · 获赞 72 · 访问量 8826

猜你喜欢

转载自blog.csdn.net/ambzheng/article/details/104483754