Go 中的 XML HTTP 发布

标签 xml go

我正在尝试创建一个使用 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/

相关文章:

SQL XML 列的元素来分隔列

xml - 从行创建 XML 元素

java - 从结构非常不同的 Java 对象生成 XML 文档

go - 向 TCP 服务器发送多个请求失败

go - 处理依赖注入(inject)

go - Go 中的同时变量赋值与单独变量赋值不同

php - 如何使用 phpstorm 评估特定命名空间的 xpath?

xml - XSLT 用户定义函数

Golang参数多态?

session - 错误 : non-declaration statement outside function body on redisstor