使xml在http post golang中发送

时间:2017-07-21 08:24:09

标签: xml go xml-parsing http-post

以下是我要形成的预期req xml

<custom key="234234e324e4">
<document name="sample" location="http://example.com">
</document>
</custom>

制作这个xml我使用了以下go代码

 type Documentxml struct {
    XMLName  xml.Name `xml:"document"`
    Name  string   `xml:"name,attr"`
    Location string   `xml:"location,attr"`
}
type DeleteXml struct {
    XMLName  xml.Name    `xml:"custom"`
    Key   string      `xml:"key,attr"`
    Document Documentxml `xml:"document"`
}

并使用以下代码将值插入其中

&#13;
&#13;
var requestxml DeleteXml
    requestxml.Key = "12321321"
    requestxml.Document.Name = "sample"
    requestxml.Document.Location = "www.//sample.com"
bytexml, err := xml.Marshal(&requestxml)
	client := &http.Client{}
	url := "http://localhost:8080/searchblox/api/rest/docdelete"
	// build a new request, but not doing the POST yet
	req, err := http.NewRequest("POST", url, bytes.NewBuffer(bytexml))
	if err != nil {
		fmt.Println(err)
	}
req.Header.Add("Content-Type", "application/xml; charset=utf-8")
	// now POST it
	resp, err := client.Do(req)
	if err != nil {
		fmt.Println(err)
	}
	fmt.Println(resp)
&#13;
&#13;
&#13;

但是这里形成的请求并不像我预期的那样形成 请求xml形成的是:{{} 12321321 {{}示例www .// sample.com}} 请告诉我这里出了什么问题

1 个答案:

答案 0 :(得分:1)

您的XML定义是正确的,并且您获得了预期的格式。但是在你的问题中。字段requestxml.Document.Location的网址格式值不正确,根据您的服务器不确定这是否有问题。

播放链接:https://play.golang.org/p/oCkteDAVgZ

输出:

<custom key="12321321">
  <document name="sample" location="http://www.sample.com"></document>
</custom>

修改

可能是您的服务器期望带有标头的XML。如下 -

<?xml version="1.0" encoding="UTF-8"?>
<custom key="12321321">
  <document name="sample" location="http://www.sample.com"></document>
</custom>

您的更新代码包含标题,播放链接:https://play.golang.org/p/n4VYXxLE6R