2017-07-21 172 views
1

以下是我的预期REQ XML来形成使得XML在HTTP POST golang发送

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

和下面的代码中插入值进去

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

但这里要求形成并不像我想像的要形成 请求XML形成为:{{} {12321321 {}样品www.//sample.com}} 请建议什么是这里

脚麻
+0

的一个问题是XMLName是Documentxml和DeleteXml空。因此,请填写空的“{}”值。 –

+0

应该提到什么 –

回答

1

你的XML定义是正确的,你会得到预期的格式。但在你的问题。字段requestxml.Document.Location具有不正确的URL格式值,不确定这是否可能是您的服务器的问题。

播放链接: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