go语言实现post、get请求及设置header、cookie
package main
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"unsafe"
)
func Post() {
client := &http.Client{}
// 设置请求体,json格式
song := make(map[string]string)
song["mldm"] = "01"
bytesData, _ := json.Marshal(song)
req, err := http.NewRequest("POST", "https://yz.chsi.com.cn/zsml/pages/getZy.jsp",
bytes.NewBuffer([]byte(bytesData)))
if err != nil {
fmt.Println("Fatal error ", err.Error())
}
//设置请求头
req.Header.Set("content-type", "application/json")
req.Header.Set("cookie", "123456")
req.Header.Set("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36")
resp, err := client.Do(req)
defer resp.Body.Close()
content, err := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Println("Fatal error ", err.Error())
}
//fmt.Println(string(content)) // 直接打印
str := (*string)(unsafe.Pointer(&content)) //转化为string,优化内存
fmt.Println(*str)
}
func Get() {
client := &http.Client{}
req, err := http.NewRequest("GET", "https://www.runoob.com/html/html-tutorial.html",
nil)
if err != nil {
fmt.Println("Fatal error ", err.Error())
}
//设置请求头
req.Header.Set("content-type", "application/json")
req.Header.Set("cookie", "123456")
req.Header.Set("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36")
resp, err := client.Do(req)
defer resp.Body.Close()
content, err := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Println("Fatal error ", err.Error())
}
//fmt.Println(string(content)) // 直接打印
str := (*string)(unsafe.Pointer(&content)) //转化为string,优化内存
fmt.Println(*str)
}
func main() {
Post()
Get()
}