我是golang的新手,但我正在尝试向mojang api发出http GET请求,以获取玩家名称的UUID。这是我的代码。
func getHTTP(url string) (response string) {
client := &http.Client{}
req, err := http.NewRequest("GET", url, nil)
req.Header.Add("Content-Type", "application/json")
if err != nil {
return string(err.Error())
}
resp, err := client.Do(req)
if err != nil {
return string(err.Error())
}
defer resp.Body.Close()
body, e := ioutil.ReadAll(resp.Body)
if err != nil {
return string(e.Error())
}
return string(body)
}
func main() {
fmt.Printf(getHTTP("https://api.mojang.com/users/profiles/minecraft/paultje52"))
}
我得到的是带有403错误(请求被阻止)的html文档,就像您在这里看到的那样。<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<HTML><HEAD><META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=iso-8859-1">
<TITLE>ERROR: The request could not be satisfied</TITLE>
</HEAD><BODY>
<H1>403 ERROR</H1>
<H2>The request could not be satisfied.</H2>
<HR noshade size="1px">
Request blocked.
We can't connect to the server for this app or website at this time. There might be too much traffic or a configuration error. Try again later, or contact the app or website owner.
<BR clear="all">
If you provide content to customers through CloudFront, you can find steps to troubleshoot and help prevent this error by reviewing the CloudFront documentation.
<BR clear="all">
<HR noshade size="1px">
<PRE>
Generated by cloudfront (CloudFront)
Request ID: JxLUo2aufLong500lqBzESwB0yKSV4aE8DReo3g-0arxXmJSfS5c8g==
</PRE>
<ADDRESS>
</ADDRESS>
</BODY></HTML>
但是,当我使用google chrome或postman(具有相同ip的同一台机器)访问完全相同的URL时,我从mojang API得到了正常响应。{
"name": "Paultje52",
"id": "895933a3f98b4bd697515673a04d632e"
}
我有做错什么吗,还是go的问题?还是阻止go提出的CloudFront请求?
最佳答案
看起来该网站已阻止默认用户代理。
使用以下行进行更改,一切都会正常进行
req.Header.Set("User-Agent", "test")
关于go - 使用go向mojang API发出请求会得到403,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63646640/