英文:
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!
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论