在HTTP请求中设置用户代理

huangapple go评论92阅读模式
英文:

Set UserAgent in http request

问题

我正在尝试让我的Go应用程序指定自己作为特定的“UserAgent”,但是在net/http中找不到任何关于如何做到这一点的信息。我正在创建一个http.Client,并使用它通过client.Get()进行Get请求。

是否有一种方法可以在Client中设置UserAgent,或者根本不行?

英文:

I'm trying to make my Go application specify itself as a specific UserAgent, but can't find anything on how to go about doing this with net/http. I'm creating an http.Client, and using it to make Get requests, via client.Get().

Is there a way to set the UserAgent in the Client, or at all?

答案1

得分: 124

当创建请求时,请使用request.Header.Set("key", "value")

package main

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

func main() {
        client := &http.Client{}

        req, err := http.NewRequest("GET", "http://httpbin.org/user-agent", nil)
        if err != nil {
                log.Fatalln(err)
        }

        req.Header.Set("User-Agent", "Golang_Spider_Bot/3.0")

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

        defer resp.Body.Close()
        body, err := io.ReadAll(resp.Body)
        if err != nil {
                log.Fatalln(err)
        }

        log.Println(string(body))

}

结果:

2012/11/07 15:05:47 {
  "user-agent": "Golang_Spider_Bot/3.0"
}

附注:http://httpbin.org非常适合测试这种类型的事情!

英文:

When creating your request use request.Header.Set("key", "value"):

package main

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

func main() {
        client := &http.Client{}

        req, err := http.NewRequest("GET", "http://httpbin.org/user-agent", nil)
        if err != nil {
                log.Fatalln(err)
        }

        req.Header.Set("User-Agent", "Golang_Spider_Bot/3.0")

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

        defer resp.Body.Close()
        body, err := io.ReadAll(resp.Body)
        if err != nil {
                log.Fatalln(err)
        }

        log.Println(string(body))

}

Result:

2012/11/07 15:05:47 {
  "user-agent": "Golang_Spider_Bot/3.0"
}

P.S. http://httpbin.org is amazing for testing this kind of thing!

huangapple
  • 本文由 发表于 2012年11月7日 13:17:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/13263492.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定