我能够使用SoapUI将zip文件与完全相同的SOAP请求附加在一起,但是对于使用SAAJ Api的Java无法附加。这是我在SOAPUI和JAVA中使用的SOAP请求:
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:dep="endpoint">
<soapenv:Header/>
</soapenv:Header>
<soapenv:Body>
<dep:projectName>projectName</dep:projectName>
<dep:content>cid:myFile.zip</dep:content>
</soapenv:Body>
</soapenv:Envelope>
现在这是我在JAVA中用于发出SOAP请求并附加文件的代码。该代码能够成功发送SOAP请求,但是无法将zip文件附加到其中。
SOAPConnection connection = null;
MessageFactory factory = null;
SOAPMessage message = null;
SOAPHeader header = null;
SOAPPart soapPart = null;
SOAPEnvelope envelope = null;
SOAPElement headerElement = null;
SOAPBody body = null;
SOAPElement initialBody = null;
SOAPElement projectName = null;
SOAPElement version = null;
AttachmentPart attachment = null;
SOAPElement content = null;
SOAPConnectionFactory soapConnectionFactory = null;
MessageContext context = null;
SOAPMessage response = null;
URL endpoint = null;
try {
factory = MessageFactory.newInstance();
message = factory.createMessage();
header = message.getSOAPHeader();
soapPart = message.getSOAPPart();
//Namespaces
envelope = soapPart.getEnvelope();
envelope.addNamespaceDeclaration("dep", "NAMESPACE");
//SOAP Body
body = message.getSOAPBody();
projectName = body.addChildElement("projectName", "dep");
projectName.addTextNode("projectName");
//Attachment
File uploadFile = new File("myFile.zip");
DataHandler dh = new DataHandler(new FileDataSource(uploadFile));
attachment = message.createAttachmentPart(dh);
//InputStream targetStream = new FileInputStream(uploadFile);
//attachment.setRawContent(targetStream, Files.probeContentType(uploadFile.toPath()));
System.out.println("The file size is " + attachment.getSize());
attachment.setContentType("application/octet-stream");
attachment.setContentId("myFile.zip");
message.addAttachmentPart(attachment);
content = initialBody.addChildElement("content","dep");
content.addTextNode("cid:" + attachment.getContentId());
message.saveChanges();
//Response
soapConnectionFactory = SOAPConnectionFactory.newInstance();
connection = soapConnectionFactory.createConnection();
endpoint = new URL("endpoint");
response = connection.call(message, endpoint);
response.writeTo(System.out);
}
catch(Exception e) {
e.printStackTrace();
}
finally{
try {
connection.close();
}
catch(Exception e){
}
}
此行:“ response.writeTo(System.out)”产生以下输出。
The file size is 21426
<S:Fault xmlns:ns4="http://www.w3.org/2003/05/soap-envelope">
<faultcode>S:Server</faultcode>
<faultstring> Project upload failed. No file was attached. </faultstring>
有人成功获取了一个zip文件来附加其SOAP请求吗?如果有人能够使用Java,curl或其他任何东西将文件附加到其SOAP请求中,我将愿意使用其他库。