go - 使用go向mojang API发出请求会得到403

标签 go

我是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/

相关文章:

sockets - 无需使用 http.Serve 即可激活 Go TLS Socket 服务器服务

go - map/reduce/filter/等的惯用替换

go - 非平凡代码golang的执行时间为零

angularjs - 为什么找不到我的图像根目录

amazon-web-services - 您能否使用 Javascript 以外的语言使用 Lambda@Edge 修改 AWS CloudFront 事件上的 URI?

ubuntu - 运行用 Go 编写的可执行文件时找不到文件

json - 解码 json 以反射(reflect)结构

golang, combine 2 方法内容相同

Go net/http 在高负载下内存泄漏

json - 取消具有可变数量的相似字段的 JSON 对象