发布于 5年前

Golang自定义http请求

 package main

import (
    "io/ioutil"
    "log"
    "net/http"
    "unsafe"
)

func main() {
    req, _ := http.NewRequest("GET", "https://www.baidu.com/s", nil)

    // 请求头
    req.Header.Add("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36")

    // 请求参数
    q := req.URL.Query()
    q.Add("word", "golang")
    req.URL.RawQuery = q.Encode()

    client := &http.Client{}

    resp, err := client.Do(req)
    if err != nil {
        log.Fatal(err)
        return
    }

    body, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        log.Fatal(err)
        return
    }
    // 记得关闭流
    defer resp.Body.Close()

    // 转文本
    respStr := *(*string)(unsafe.Pointer(&body))
    log.Println(respStr)
}
©2020 edoou.com   京ICP备16001874号-3