使xml发送到http post golang中

following is my expected req xml to be formed

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

to make this xml i have used following go code

 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"`
}

and following code to insert values into it

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)

but here request formed is not as i expected to be formed request xml formed is: {{ } 12321321{{ } sample www.//sample.com}} please suggest what is going wrong here

</div>
dongmopu6734
dongmopu6734 应该提到什么
大约 3 年之前 回复
doumianfeng5065
doumianfeng5065 一个问题是DocumentName和DeleteXml中的XMLName为空。因此,空{}值。
大约 3 年之前 回复

1个回答

Your XML definition is correct and you're getting expected format. However in your question. Field requestxml.Document.Location has incorrect URL format value, not sure if this could be problem as per your server.

Play Link: https://play.golang.org/p/oCkteDAVgZ

Output:

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

EDIT:

May be your server is expecting XML with header. Like below-

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

Your update code with header, play link: https://play.golang.org/p/n4VYXxLE6R

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问