Go http请求添加Cookie 跟header相关的代码

MCtech 355 0
package main

import (
    "fmt"
    "github.com/go-resty/resty/v2"
    "net/http"
)

func GET(URL string) {
    //创建resty client实例
    cookies := []*http.Cookie{
        &http.Cookie{
            Name:  "go-resty-1",
            Value: "This is cookie 1 value",
        },
        &http.Cookie{
            Name:  "go-resty-2",
            Value: "This is cookie 2 value",
        },
    }
    client := resty.New()
    resp, err := client.R().
        EnableTrace().
        Get(URL)

    client.SetHeaders(map[string]string{
        "Content-Type": "application/json",
        "User-Agent":   "My custom User Agent String",
    })

    // Setting a cookies into resty's current request
    client.SetCookies(cookies)

    //4.。。。Post setBody
    fmt.Println("Response Info:")
    fmt.Println("  Error      :", err)
    fmt.Println("  Status Code:", resp.StatusCode())
    fmt.Println("  Status     :", resp.Status())
    fmt.Println("  Proto      :", resp.Proto())
    fmt.Println("  Time       :", resp.Time())
    fmt.Println("  Received At:", resp.ReceivedAt())
    fmt.Println("  Body       :\n", resp)
    fmt.Println()

    // Explore trace info
    fmt.Println("Request Trace Info:")
    ti := resp.Request.TraceInfo()
    fmt.Println("  DNSLookup     :", ti.DNSLookup)
    fmt.Println("  ConnTime      :", ti.ConnTime)
    fmt.Println("  TCPConnTime   :", ti.TCPConnTime)
    fmt.Println("  TLSHandshake  :", ti.TLSHandshake)
    fmt.Println("  ServerTime    :", ti.ServerTime)
    fmt.Println("  ResponseTime  :", ti.ResponseTime)
    fmt.Println("  TotalTime     :", ti.TotalTime)
    fmt.Println("  IsConnReused  :", ti.IsConnReused)
    fmt.Println("  IsConnWasIdle :", ti.IsConnWasIdle)
    fmt.Println("  ConnIdleTime  :", ti.ConnIdleTime)
    fmt.Println("  RequestAttempt:", ti.RequestAttempt)
    fmt.Println("  RemoteAddr    :", ti.RemoteAddr.String())
    fmt.Println("Cookies   :", client.Cookies[1])

}
func main() {
    GET("https://www.baidu.com")
}

发表评论 取消回复
表情 图片 链接 代码

分享