locking(null, callback);
} catch (AxisFault e) {
System.out.println("Exception occur!");
System.out.println(e.getMessage());
}
synchronized (callback) {
if (!finish) {
try {
callback.wait(1000);
} catch (Exception e) {
}
}
}
} catch (AxisFault e) {
e.printStackTrace();
System.out.println(e.getMessage());
} finally {
try {
sender.cleanup();
} catch (Exception e) {
}
}
}
}
注意红色并加粗部分的代码,为了抓到服务端抛过来的SoapFault我们必须使用非阻塞式,因此我们在onFault处,进行接受服务端错误的处理。
注意:
我们调用Service端时没有传入Service端所需要的request的参数:
// sender.sendReceiveNonBlocking(request,callback);
sender.sendReceiveNonBlocking(null,callback);
这将构成Service端抛出SoapFault。
来看运行效果:
四、使用SWA(Soap WithAttachment)来进行附件传送
有了上面两个例子的基础后,我们将使用这个例子来结束Axis2中的Soap特性的教学。
在Axis2中传输附件有两种形式,一种叫MTOM,一种就是SWA。
SWAP即Soap With Attachment,这是业界的标准。
所谓的SWA传输,即客户端把需要上传的文件,编译成两进制代码凌晨随着soap的request一起推送到服务端,该两进制代码以AttachmentId的形式来表示,即如下这样的一个soap body:
<soapenv:Body>
<uploadFile xmlns="http://attachment.axis2.sky.org">
<name>test.jpg</name>
<attchmentID>urn:uuid:8B43A26FEE1492F85A1343628038693</attchmentID>
</uploadFile>
</soapenv:Body>
服务端收到该soap的request可以直接使用如下的语句将这个AttachmentId还原成输出流:
DataHandler dataHandler = attachment.getDataHandler(attchmentID);
File file = new File(uploadFilePath.toString());
fileOutputStream = new FileOutputStream(file);
dataHandler.writeTo(fileOutputStream);
fileOutputStream.flush();
在我们这个例子内,我们将使用客户端上传一个jpg文件,服务端收到该jpg文件(可以是任何的两进制文件)后解析后存入服务端的一个目录。
先来看服务端代码
org.sky.axis2.attachment.FileUploadService
package org.sky.axis2.attachment;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.activation.DataHandler;
import org.apache.axiom.attachments.Attachments;
import org.apache.axis2.context.MessageContext;
import org.sky.axis2.util.UUID;
public class FileUploadService {
public String uploadFile(String name, String attchmentID) throws Exception {
FileOutputStream fileOutputStream = null;
StringBuffer uploadFilePath = new StringBuffer();
String fileNamePrefix = "";
String fileName = "";
try {
MessageContext msgCtx = MessageContext.getCurrentMessageContext();
Attachments attachment = msgCtx.getAttachmentMap();
DataHandler dataHandler = attachment.getDataHandler(attchmentID);
fileNamePrefix = name.substring(name.indexOf("."), name.length());
fileName = UUID.getUUID();
System.out.println("fileName=====" + fileName);
System.out.println("fileNamePrefix====" + fileNamePrefix);
uploadFilePath.append("D:/upload/axis2/");
uploadFilePath.append(fileName);
uploadFilePath.append(fileNamePrefix);
System.out
.println("uploadFilePath====" + uploadFilePath.toString());
File file = new File(uploadFilePath.toString());
fileOutputStream = new FileOutputStream(file);
dataHandler.writeTo(fileOutputStream);
fileOutputStream.flush();
} catch (Excep