【问题标题】:HTTP POST with an XML body and file as attachment带有 XML 正文和文件作为附件的 HTTP POST
【发布时间】:2018-06-18 11:25:26
【问题描述】:

我有一个问题。我正在开发一个与 SOAP 服务器联系的 Go 客户端。我应该在正文中使用 SOAP 消息向服务器发送 HTTP POST 请求。我还必须在请求中附上一个文件。我该怎么做?

到目前为止,我只能将 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

【问题讨论】:

    标签: http post go soap


    【解决方案1】:

    您应该使用支持添加附件的 SOAP 库,或者您应该了解 SOAP 标准以包含附件。

    来自https://www.w3.org/TR/SOAP-attachments

    以下示例显示了带有附加信息的 SOAP 1.1 消息 已签名索赔表 (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 包轻松生成多部分。

    这是另一个 sn-p,它创建一个多部分表单,其中包含来自文件系统(来自 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
    

    【讨论】:

      猜你喜欢
      • 2019-10-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-12
      • 2022-01-07
      相关资源
      最近更新 更多