带有 client.crt 和 client.key 的 https 请求
时间:2024-04-07
浏览:320
作者:佚名
本篇文章主要是结合我之前面试的各种经历和实战开发中遇到的问题解决经验整理的,希望这篇《带有 client.crt 和 client.key 的 https 请求》对你有很大帮助!欢迎收藏,分享给更多的需要的朋友学习~
我想向 https 服务器发送 post 请求并获取响应。这是我在curl 中所做的事情,效果很好。
curl --key ./client.key --cert ./client.crt https://test-as.sgx.trustedservices.intel.com:443/attestation/sgx/v2/report -h '内容-类型:application/json' --data '{"key": "value"}'
这是我在 go 中尝试的代码片段。
url := "https://test-as.sgx.trustedservices.intel.com:443/attestation/sgx/v2/report"
pair, e := tls.loadx509keypair("client.crt", "client.key")
if e != nil {
log.fatal("loadx509keypair:", e)
}
client := &http.client{
transport: &http.transport{
tlsclientconfig: &tls.config{
insecureskipverify: true,
certificates: []tls.certificate{pair},
},
}}
resp, e := client.post(url, "application/json", bytes.newbufferstring(payload))
程序挂在最后一行,错误消息为
Post: dial tcp connectex: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.
我觉得我的连接建立代码有问题,而不是服务器的问题,因为服务器与curl完美配合。
解决方案
首先,永远不会使用 insecureskipverify: true,无论它看起来多么方便。相反,设置类似:
tls.Config {
ServerName: "test-as.sgx.trustedservices.intel.com",
Certificates: []tls.Certificate{pair}
}
其次,初始化 http.transport - 传递您的自定义 tls.config - 还将默认 http.transport 附带的所有其他默认 http.transport 设置清零。
其中一些零默认值可能会强制出现您可能意想不到的行为。 请参阅 here 了解如何恢复其中一些原始默认值。
理论要掌握,实操不能落!以上关于《带有 client.crt 和 client.key 的 https 请求》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注golang学习网公众号吧!
本文内容来源于互联网,如有侵权请联系删除。
近期热门
站内热门
最新文章
热门专题
