新建ImgData类,存放文件javabean
DataHandler:使用这个类型存放文件
@XmlRootElement(name="ImaData")
@XmlAccessorType(XmlAccessType.FIELD)
public class ImgData {private Integer id;@XmlMimeType("application/octet-stream")private DataHandler imgData; //文件public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public DataHandler getImgData() {return imgData;}public void setImgData(DataHandler imgData) {this.imgData = imgData;}
}
Webservice接口, @WebService(name="iHello2")
@SOAPBinding(style = SOAPBinding.Style.RPC)
@MTOM
public interface IHello2 {public void printContext();public ImgData getById(@WebParam(name="imgData")ImgData imgData);
}
实现类 @WebService(serviceName="HelloService",portName="HelloServicePort",
targetNamespace="http://service.lc.com/",endpointInterface="com.lc.service2.IHello2")
public class IHello2Imp implements IHello2 {@Resourceprivate WebServiceContext context;@Overridepublic void printContext() {MessageContext ctx = context.getMessageContext();Set<String> set = ctx.keySet();for(String key : set) {System.out.println("{" + key + "," + ctx.get(key) + "}");try {System.out.println("key.scope:" + ctx.getScope(key));} catch (Exception e) {System.out.println("scope not found");}}}@Overridepublic ImgData getById(ImgData custom) {if(custom.getId() == 1) {File file = new File("f:" + File.separator + "原文件.png");System.out.println(file.exists());custom.setImgData(new DataHandler(new FileDataSource(file)));}return custom;}}
这里需要在f盘下放一个“原文件.png”的文件,当然也可以改创建webservice类SoapService2,运行
public class SoapService2 {public static void main(String[] args) {Endpoint.publish("http://localhost:8080/HelloService2", new IHello2Imp());System.out.println("run success");}}
生成客户端代码 在cmd使用wsimport -p com.lc.client2 -keep http://localhost:8080/HelloService2?wsdl
创建客户端类SoapClient.java,运行
public class SoapClient {public static void main(String[] args) throws MalformedURLException {QName qName = new QName("http://service.lc.com/", "HelloService");HelloService helloService = new HelloService(new URL("http://localhost:8080/HelloService2?wsdl"), qName);IHello2 hello2 = helloService.getPort(IHello2.class);hello2.printContext();ImgData imgData = new ImgData();imgData.setId(1);ImgData imgData2 = hello2.getById(imgData);DataSource ds = imgData2.getImgData().getDataSource();String ctt = ds.getContentType();System.out.println("ContentType:" + ctt);try {InputStream is = ds.getInputStream();OutputStream os = new FileOutputStream("F:" + File.separator + "t1.png");byte[] bytes = new byte[1024];//一次读取1024byteint i = 0;while((i = is.read(bytes)) != -1){os.write(bytes, 0, i);}} catch (IOException e) {e.printStackTrace();} }
}
运行结果 参考资料
[1].http://wuhongyu.iteye.com/blog/807470
[2].https://my.oschina.net/liu13430/blog/373940?fromerr=WmdtQOoY
[3].http://clq9761.iteye.com/blog/976029/