【问题标题】:How to attach a file (pdf, jpg, etc) in a SOAP POST request?如何在 SOAP POST 请求中附加文件(pdf、jpg 等)?
【发布时间】:2018-07-17 00:52:26
【问题描述】:

我有下一个方法:

public String uploadFile(String body, File uploadFile) throws Exception {

        String xmlBody = startEnvelopeTag + body + endEnvelopeTag;

        URL urlObj = new URL(urlWS);
        HttpURLConnection connection = (HttpURLConnection) urlObj.openConnection();

        connection.setRequestProperty("Connection", "Keep-Alive");
        connection.setRequestMethod("POST");
        connection.setRequestProperty("SOAPAction", action);
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setUseCaches(false);

        DataOutputStream wr = new DataOutputStream(connection.getOutputStream());

        // Now I attach the xml body...

        wr.writeBytes(xmlBody);
        wr.flush();

        // Now I Attach file...

        FileInputStream inputStream = new FileInputStream(uploadFile);

        byte[] buffer = new byte[4096];

        int bytesRead = -1;

        while ((bytesRead = inputStream.read(buffer)) != -1) {
            wr.write(buffer, 0, bytesRead);
        }

        wr.flush();
        wr.close();

        int responseCode = connection.getResponseCode();

        BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));

        String inputLine;

        StringBuffer response = new StringBuffer();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }

        in.close();

        return response.toString();
    }

但是我收到一个代码 500。如果我评论附件的部分,服务会发送一个代码 200,但错误是不存在的文件(进入 xml 响应)。

这是我的身体:

<?xml version="1.0" encoding="UTF-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:sch="http://www.ibm.com/xmlns/db2/cm/beans/1.0/schema" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
   <soap:Body>
      <sch:CreateItemRequest>
         <sch:AuthenticationData>
            <sch:ServerDef>
               <sch:ServerType>ICM</sch:ServerType>
               <sch:ServerName>icmnlsdb</sch:ServerName>
            </sch:ServerDef>
            <sch:LoginData>
               <sch:UserID>xxxxxx</sch:UserID>
               <sch:Password>xxxxxx</sch:Password>
            </sch:LoginData>
         </sch:AuthenticationData>
         <sch:Item>
            <sch:ItemXML>
               <sch:X field1="x" field2="y" field3="z">
                  <sch:ICMBASE>
                     <sch:resourceObject xmlns="http://www.ibm.com/xmlns/db2/cm/api/1.0/schema" MIMEType="application/pdf">
                        <sch:label name="test" />
                     </sch:resourceObject>
                  </sch:ICMBASE>
               </sch:X>
            </sch:ItemXML>
         </sch:Item>
      </sch:CreateItemRequest>
   </soap:Body>
</soap:Envelope>

在 SOAP-UI 中,我可以附加文件,但我需要用 Java 制作。

知道如何附加正文和文件吗?

【问题讨论】:

    标签: java web-services soap


    【解决方案1】:

    最后,我使用 SAAJ API。我用这种方法构造 XML 和 SOAP 消息:

    // Create SOAP Message
    private static SOAPMessage createSOAPRequest(File uploadFile, Map<String, String> values, String fileName, String[] attributes) throws Exception {
    
            MessageFactory messageFactory = MessageFactory.newInstance();
            SOAPMessage soapMessage = messageFactory.createMessage();
            SOAPPart soapPart = soapMessage.getSOAPPart();
    
            // SOAP Header
            MimeHeaders headers = soapMessage.getMimeHeaders();
            headers.addHeader("SOAPAction", ACTION);
    
            // SOAP Envelope
            SOAPEnvelope envelope = soapPart.getEnvelope();
            envelope.addNamespaceDeclaration("sch", NAMESPACE);
    
            // SOAP Body
            SOAPBody soapBody = envelope.getBody();
            SOAPElement createItemRequest = soapBody.addChildElement("CreateItemRequest", "sch");
                SOAPElement authenticationData = createItemRequest.addChildElement("AuthenticationData", "sch");
                    SOAPElement serverDef = authenticationData.addChildElement("ServerDef", "sch");
                        SOAPElement serverType = serverDef.addChildElement("ServerType", "sch");
                        serverType.addTextNode("ICM");
                        SOAPElement serverName = serverDef.addChildElement("ServerName", "sch");
                        serverName.addTextNode("icmnlsdb");
                    SOAPElement loginData = authenticationData.addChildElement("LoginData", "sch");
                        SOAPElement userID = loginData.addChildElement("UserID", "sch");
                        userID.addTextNode("*******");
                        SOAPElement password = loginData.addChildElement("Password", "sch");
                        password.addTextNode("*******");
                SOAPElement item = createItemRequest.addChildElement("Item", "sch");
                    SOAPElement itemXML = item.addChildElement("ItemXML", "sch");
                        SOAPElement type = itemXML.addChildElement(values.get("Type"), "sch");
    
                        for(int i = 0; i<attributes.length;i++)
                            type.setAttribute(attributes[i],values.get(attributes[i]));
    
                            SOAPElement icmBASE = type.addChildElement("ICMBASE", "sch");
                                SOAPElement resourceObject = icmBASE.addChildElement("resourceObject", "sch");
    
                                resourceObject.setAttribute("MIMEType",Files.probeContentType(uploadFile.toPath()));
    
                                resourceObject.setAttribute("xmlns","http://www.ibm.com/xmlns/db2/cm/api/1.0/schema");
                                    SOAPElement label = resourceObject.addChildElement("label", "sch");
                                    label.setAttribute("name",fileName);
    
            AttachmentPart attachment = soapMessage.createAttachmentPart();
    
            InputStream targetStream = new FileInputStream(uploadFile);
    
            attachment.setRawContent(targetStream, Files.probeContentType(uploadFile.toPath()));
    
            attachment.setContentId(fileName);
    
            soapMessage.addAttachmentPart(attachment);
    
            soapMessage.saveChanges();
    
            return soapMessage;
    }
    

    然后我用这个方法拨打电话:

    // HTTP POST Upload
    public void doUpload(File uploadFile, Map<String, String> values, String nombreArchivo, String[] nombreAtributos) throws Exception{
    
                // Create SOAP Connection
                SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance();
                SOAPConnection soapConnection = soapConnectionFactory.createConnection();
    
                // Send SOAP Message to SOAP Server
                SOAPMessage soapResponse = soapConnection.call(createSOAPRequest(uploadFile,values,nombreArchivo,nombreAtributos), urlWS);
    
                soapConnection.close(); 
    }
    

    您好。

    【讨论】:

      猜你喜欢
      • 2012-01-24
      • 1970-01-01
      • 2022-01-11
      • 2021-07-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-11
      • 2017-04-30
      相关资源
      最近更新 更多