简体   繁体   中英

How to attach a file (pdf, jpg, etc) in a SOAP POST request?

I have the next method:

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();
    }

But I receive a code 500. If I comment the part of the attach file, the service send a code 200, but with an error of the non-existent file (into of xml response).

This is my body:

<?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>

In SOAP-UI I can attach file, but I need make this in Java.

Any idea how I could attach the body and then the file?

Finally, I use SAAJ API. I construct the XML and SOAP Message with this method:

// 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;
}

And then I make the call with this method:

// 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(); 
}

Greetings.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM