golang:模擬http post請求


  1,發送http post請求(客戶端)

func httppost()  {
	data :=`{"type":"10","msg":"hello."}`
	request, _ := http.NewRequest("POST", "http://0.0.0.0:8090/msg", strings.NewReader(data))
	//post數據並接收http響應
	resp,err :=http.DefaultClient.Do(request)
	if err!=nil{
		fmt.Printf("post data error:%v\n",err)
	}else {
		fmt.Println("post a data successful.")
		respBody,_ :=ioutil.ReadAll(resp.Body)
		fmt.Printf("response data:%v\n",string(respBody))
	}
}

  2,接收方法(服務端)

package main

import (
	"net/http"
	"io/ioutil"
	"fmt"
)

func main()  {
	//設置路由和接收HTTP請求的方法
	mux :=http.NewServeMux()
	mux.HandleFunc("/msg",recvHandle)
	//設置http服務
	server :=&http.Server{
		Addr:    "0.0.0.0:8090",
		Handler: mux,
	}
	//啟動監聽
	server.ListenAndServe()
}
func recvHandle(w http.ResponseWriter, r *http.Request)  {
	body,_ :=ioutil.ReadAll(r.Body)
	fmt.Println(string(body))
	fmt.Fprintf(w,"3q your msg.")
}

  3,執行結果

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM