1. 程式人生 > 實用技巧 >Go net/http包,原生http客戶端使用

Go net/http包,原生http客戶端使用

Go net/http包,原生http客戶端使用

  • http包提供的兩個快速Get,Post請求的函式定義如下(go不支援函式過載)

    • func Get(url string) (resp *Response, err error)

    • func Post(url, contentType string, body io.Reader) (resp *Response, err error)

    • func PostForm(url string, data url.Values) (resp *Response, err error)

      PostForm 是contenType值為 application/x-www-form-urlencoded

      時的Post

  • 要管理HTTP客戶端的頭域、重定向策略和其他設定,需自定義Client

  • 要管理代理、TLS配置、keep-alive、壓縮和其他設定,需自定義Transport

簡單get/post請求的程式碼

package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"net/url"
)

func main() {
	params := url.Values{}
	params.Set("password", "zhaofan")
	GetWithParam("http://10.93.181.200:8090/sh/encrypt", params)
	//
	data := make(map[string]interface{})
	data["id"] = "1"
	data["name"] = "部落格"
	Post("http://10.93.181.200:8090/sh/json", data)
}

// 無請求頭,無引數get
func Get(urlStr string) {
	res, _ := http.Get(urlStr)
	defer res.Body.Close()
	bodyBytes, _ := ioutil.ReadAll(res.Body)
	body := string(bodyBytes)
	fmt.Print(body)
}

// 無請求頭, 有引數get
func GetWithParam(urlStr string, params url.Values) {
	Url, _ := url.Parse(urlStr)
	Url.RawQuery = params.Encode()
	urlPath := Url.String()
	// 列印拼接後的url, 形如https://www.xxx.com?k=v&k2=v2
	fmt.Println(urlPath)
	resp, _ := http.Get(urlPath)
	defer resp.Body.Close()
	bodyBytes, _ := ioutil.ReadAll(resp.Body)
	body := string(bodyBytes)
	fmt.Println(string(body))
}

// 帶json引數的post請求
func Post(urlStr string, v interface{}) {
	bytesData, _ := json.Marshal(v)
	resp, _ := http.Post(urlStr, "application/json", bytes.NewReader(bytesData))
	defer resp.Body.Close()
	bodyBytes, _ := ioutil.ReadAll(resp.Body)
	body := string(bodyBytes)
	fmt.Println(body)
}