golang的各種請求方法實現

1. GET請求

func httpGet() {
	resp, err := http.Get("http://www.baidu.com")
	if err != nil {
		// handle error
		fmt.Println(err.Error())
	} else {
		body, err := ioutil.ReadAll(resp.Body)
		if err != nil {
			// handle error
			fmt.Println(err.Error())
		}
		fmt.Println(string(body))
	}
}

2. post請求

1. http.Post方式

func httpPost() {
	// 使用這個方法的話,第二個參數要設置成”application/x-www-form-urlencoded”,否則post參數無法傳遞。
	resp, err := http.Post("127.0.0.1:8080/user/login",
		"application/x-www-form-urlencoded",
		strings.NewReader("name=zhangsan"))
	if err != nil {
		fmt.Println(err.Error())
	} else {
		body, err := ioutil.ReadAll(resp.Body)
		if err != nil {
			// handle error
			fmt.Println(err.Error())
		}
		fmt.Println(string(body))
	}
}

2. http.PostForm方法

func httpPostForm() {
	resp, err := http.PostForm("127.0.0.1:8080/user/login",
		url.Values{"name": {"zhangsan"}, "password": {"123456"}})
	if err != nil {
		fmt.Println(err.Error())
	} else {
		body, err := ioutil.ReadAll(resp.Body)
		if err != nil {
			// handle error
			fmt.Println(err.Error())
		}
		fmt.Println(string(body))
	}
}

3. 比較複雜的請求,http.Do方法

//有時需要在請求的時候設置頭參數、cookie之類的數據,就可以使用http.Do方法。

1. 使用strings.NewReader()傳參

func httpDo(name string, password string) {
	client := &http.Client{}
	// 設置請求體
	data := url.Values{}
	// key,value必須爲字符串類型
	data.Add("name", name)
	data.Add("password", password)
	// 請求中三個參數依次爲 請求方法, 請求url, 請求體
	req, err := http.NewRequest("POST", "127.0.0.1:8080/user/login", strings.NewReader(data.Encode()))
	if err != nil {
		// handle error
	}
	// 設置請求頭
	//必須要設定Content-Type爲application/x-www-form-urlencoded,post參數纔可正常傳遞
	req.Header.Set("Content-Type", "application/x-www-form-urlencoded")

	resp, err := client.Do(req)
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		// handle error
	}

	fmt.Println(string(body))
}

2. 使用bytes.NewBuffer()傳參

// url:請求地址,data:POST請求提交的數據,contentType:請求體格式,如:application/json

func Post(url string, data interface{}, contentType string) string {
	jsonStr, _ := json.Marshal(data)
	req, err := http.NewRequest(`POST`, url, bytes.NewBuffer(jsonStr))
	req.Header.Add(`content-type`, contentType)
	if err != nil {
		panic(err)
	}
	defer req.Body.Close()
	// 設置超時時間
	client := &http.Client{Timeout: 5 * time.Second}
	resp, err := client.Do(req)
	if err != nil {
		panic(err)
	}
	defer resp.Body.Close()
	result, _ := ioutil.ReadAll(resp.Body)
	return string(result)
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章