我正在向基于 https 的 API 发出请求。
在 Chrome 中输入请求 URL 时,一切正常。在 Go 中使用 net/http
包执行相同的请求时,我收到有关缺少子域的错误:
"error": {
"type": "ApiUnknown",
"message": "No api specified (via subdomain)"
}
我假设 Chrome 和 Go 以某种方式发送略有不同的 http 请求,因此,我需要知道这些差异可能是什么。
在 Chrome 中,我可以使用开发者工具来查看发送的请求。
如何获取从 http
包发送的 HTTP 请求正文?
我可以做以下事情:
package main
import (
"net/http"
"os"
)
func main() {
urlStr := "https://api-name.subdomain.domain.org/page?param=value"
//client := &http.Client{}
req, err := http.NewRequest("GET", urlStr, nil)
if err != nil {
panic(err)
}
req.Write(os.Stdout) // Will this output be equal to the one being sent to the server?
//resp, err := client.Do(req)
}
输出:
GET /page?param=value HTTP/1.1
Host: api-name.subdomain.domain.org
User-Agent: Go 1.1 package http
Playground : http://play.golang.org/p/Oku0O1yiBt
但我不确定 Transport 是否在发送请求之前添加了一些东西,或者这是否真的就是全部。
最佳答案
我刚刚查看了 net/http 标准库源。正如 James Henstridge 已经回答的那样:可能会添加一些额外的授权和传输相关的 header 。但这都是严格遵守协议(protocol)的。所以我不认为那里有什么问题。
示例底部的代码应该真正打印出所有相关信息。现在,请求失败的原因取决于您的具体用例。
您是否指定了正确的子域(如错误消息所述)?
您是否设置了Content-Type
header ?服务器可能会根据您选择的子域检查适当的 Content-Type
。
这些只是我现阶段可以做出的一些假设。
关于http - 获取正在发送的 HTTP 请求正文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22704137/