我有一个问题。我在 Go 中的一个客户端上工作,它与 SOAP 服务器联系。我应该向服务器发送一个 HTTP POST 请求,请求体中包含 SOAP 消息。我还必须在请求中附上一份文件。我该怎么做?
到目前为止,我只能将 SOAP 消息放入请求中,但不知道如何将文件也包含在请求中。下面是生成请求的代码。如何在此请求中包含文件?
payload := strings.NewReader(soapDataString)
req, _ := http.NewRequest("POST", endPointUrl, payload)
req.SetBasicAuth("user", "password")
req.Header.Add("content-type", "text/xml")
req.Header.Add("cache-control", "no-cache")
req.Header.Add("SOAPAction", "")
return req
最佳答案
您应该使用支持添加附件的 SOAP 库,或者您应该了解 SOAP 标准以包含附件。
来自 https://www.w3.org/TR/SOAP-attachments
The following example shows a SOAP 1.1 message with an attached facsimile image of the signed claim form (claim061400a.tiff):
MIME-Version: 1.0 Content-Type: Multipart/Related; boundary=MIME_boundary; type=text/xml; start="<claim061400a.xml@claiming-it.com>" Content-Description: This is the optional message description. --MIME_boundary Content-Type: text/xml; charset=UTF-8 Content-Transfer-Encoding: 8bit Content-ID: <claim061400a.xml@claiming-it.com> <?xml version='1.0' ?> <SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"> <SOAP-ENV:Body> .. <theSignedForm href="cid:claim061400a.tiff@claiming-it.com"/> .. </SOAP-ENV:Body> </SOAP-ENV:Envelope> --MIME_boundary Content-Type: image/tiff Content-Transfer-Encoding: binary Content-ID: <claim061400a.tiff@claiming-it.com> ...binary TIFF image... --MIME_boundary--
它是一个多部分的 MIME 类型。你可以使用 mime/multipart包以轻松生成多部分。
这是另一个创建包含来自文件系统(来自 this blog 的任意文件)的多部分表单的片段。
file, err := os.Open(path)
if err != nil {
return nil, err
}
defer file.Close()
body := &bytes.Buffer{}
writer := multipart.NewWriter(body)
part, err := writer.CreateFormFile(paramName, filepath.Base(path))
if err != nil {
return nil, err
}
_, err = io.Copy(part, file)
err = writer.Close()
if err != nil {
return nil, err
}
req, err := http.NewRequest("POST", uri, body)
req.Header.Set("Content-Type", writer.FormDataContentType())
return req, err
关于带有 XML 正文和文件作为附件的 HTTP POST,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48167984/