我正在尝试创建一个使用 xml 的发布请求。
我知道我需要使用:
http.Post("myurl", "text/xml", body)
但我不知道如何设置要发送的实际 XML 数据。
<request>
<parameters>
<email>test@test.com</email>
<password>test</password>
</parameters>
</request>
并设置标题为Content-Type: text/xml
最佳答案
无需发出您自己的请求或手动设置内容类型,这一切都可以通过一个简单的 http.Post
调用完成:
package main
import (
"log"
"net/http"
"strings"
)
func main() {
const myurl = "http://127.0.0.1:8080"
const xmlbody = `
<request>
<parameters>
<email>test@test.com</email>
<password>test</password>
</parameters>
</request>`
resp, err := http.Post(myurl, "text/xml", strings.NewReader(xmlbody))
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
// Do something with resp.Body
}
bodyType
参数中使用的任何内容都会进入内容类型 header 。
服务器将看到:
POST / HTTP/1.1
Host: 127.0.0.1:8080
User-Agent: Go 1.1 package http
Content-Length: 127
Content-Type: text/xml
Accept-Encoding: gzip
<request>
<parameters>
<email>test@test.com</email>
<password>test</password>
</parameters>
</request>
(额外的空行是因为我选择在新行开始字符串文字)。
关于Go 中的 XML HTTP 发布,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29564032/