带有 XML 正文和文件作为附件的 HTTP POST

标签 http post go soap

我有一个问题。我在 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/

相关文章:

android - 如何在 Http post Android 中取得进展?

c++ - 将 "binary string"转换为 "const char*"以发送(网络服务器)

http - 为什么 URL 和查询字符串部分的编码不同?

java - 获取 Jersey 后端的所有输入文件

php - 我可以 POST 和 GET 到同一个 PHP 页面吗

git - 无法通过 HTTP 克隆远程 Git 镜像,但可以通过 SSH

javascript - jQuery Ajax 文件上传

regex - 使用 golang 正则表达式获取 xlsx 单元格数据?

Golang TLS 握手错误 - "first record does not look like a TLS handshake"?

web - 在抓取完整的纽约时报文章时如何规避机器人保护?