Go Http 使用案例

net/http包使用案例。

GET、POST请求示例。

get请求

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

func get(id string) {
    
    
	client := &http.Client{
    
    }
	// 创建请求
	req, _ := http.NewRequest(
		"GET",
		"https://csdn.com?id="+id,
		nil)
	// 添加请求头
	req.Header.Add("token", "a")
	// 执行
	resp, _ := client.Do(req)
	// 获取消息体
	body, _ := ioutil.ReadAll(resp.Body)
	fmt.Println(string(body))
}

post请求

func post(id string, name string) {
    
    
	client := &http.Client{
    
    }
	// 请求体
	data := make(map[string]interface{
    
    })
	data["id"] = id
	data["name"] = name
	// 转成json
	bytesData, _ := json.Marshal(data)
	// 创建请求
	req, _ := http.NewRequest(
		"POST",
		"https://csdn.com",
		bytes.NewReader(bytesData))
	// 执行
	resp, _ := client.Do(req)
	// 获取消息体
	body, _ := ioutil.ReadAll(resp.Body)
	// 打印
	fmt.Println(string(body))
}

猜你喜欢

转载自blog.csdn.net/LitongZero/article/details/108300925