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() {
	// 获取所有博客
	Get("http://localhost:8081/blogs")
	// 获取指定id博客
	params := url.Values{}
	params.Set("id", "1")
	GetWithParam("http://localhost:8081/blog", params)
	// 添加token请求头, 新增博客
	data := make(map[string]interface{})
	data["id"] = 4
	data["name"] = "下一件大事:flutter"
	headerMap := make(map[string][]string)
	headerMap["token"] = []string{"validate_me"}
	PostWithHeader("http://localhost:8081/blog", headerMap, data)
}

// 无请求头,无参数get
func Get(urlStr string) {
	res, _ := http.Get(urlStr)
	defer res.Body.Close()
	bodyBytes, _ := ioutil.ReadAll(res.Body)
	body := string(bodyBytes)
	fmt.Println(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(body)
}

// 带请求头的post请求
func PostWithHeader(urlStr string, headerMap map[string][]string, params interface{}) {
	client := &http.Client{}
	bytesData, _ := json.Marshal(params)
	req, _ := http.NewRequest("POST", urlStr, bytes.NewReader(bytesData))
	if headerMap != nil {
		for k, v := range headerMap {
			//req.Header.Add(k, v[0])
			//req.Header.Set(k, v[0])
			req.Header[k] = v //原样添加请求头

		}
	}
	req.Header.Add("Content-Type", "application/json")
	resp, _ := client.Do(req)
	defer resp.Body.Close()
	bodyBytes, _ := ioutil.ReadAll(resp.Body)
	body := string(bodyBytes)
	fmt.Println(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)
}
posted @ 2020-12-15 23:00  varyuan  阅读(215)  评论(0编辑  收藏  举报