jax-ws 文件下载


1.新建接口:FileServer

import javax.activation.DataHandler;
import javax.jws.WebMethod;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
import javax.jws.soap.SOAPBinding.Style;

/**
 * 
 * @author Administrator TODO
 */
@WebService
@SOAPBinding(style = Style.RPC)
public interface FileServer {
	// download a File from server
	@WebMethod
	public DataHandler downloadFile(String fileName);
}

2.实现类:

package com.it.filedown;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.jws.WebService;
import javax.xml.ws.soap.MTOM;

/**
 * 
 * @author Administrator TODO
 */
@MTOM
@WebService(endpointInterface = "com.it.filedown.FileServer")
public class FileServerImpl implements FileServer {

	public DataHandler downloadFile(String fileName) {
		FileDataSource dataSource = new FileDataSource("c:/test/"+fileName);
		DataHandler fileDataHandler = new DataHandler(dataSource);
		return fileDataHandler;
	}

}

4.发布类:FileDownServerPublisher

package com.it.filedown;

import javax.xml.ws.Endpoint;

/**
 * 
 * @author Administrator TODO
 */
public class FileDownServerPublisher {
	public static void main(String[] args) {
		// 第一个参数是发布的URL
		// 第二个参数是SIB实现
		Endpoint.publish("http://127.0.0.1:10101/filedown", new FileServerImpl());
	}
}

3.打开cmd命令窗口切换到空白目录,输入:wsimport -keep http://localhost:10101/filedown?wsdl


4.复制生成的类到客户端的javaproject新建一个client类:

package com.it.client;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import javax.xml.namespace.QName;
import javax.xml.ws.Service;
import com.it.filedown.FileServer;

/**
 * 
 * @author Administrator TODO
 */
public class FileDownClient {
	public static void main(String[] args) {
		try {
			URL url = new URL("http://localhost:10101/filedown?wsdl");
			QName qname = new QName("http://filedown.it.com/",
					"FileServerImplService");
			Service service = Service.create(url, qname);
			FileServer fileServer = service.getPort(FileServer.class);
			byte[]  bytes = fileServer.downloadFile("123.txt");
			FileOutputStream outputStream = new FileOutputStream("E:/test.txt");
			outputStream.write(bytes);
			outputStream.flush();
			outputStream.close();
			System.out.println(" Download Successful!");
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

5.运行服务的FileDownServerPublisher类然后运行FileDownClient 




版权声明:本文为博主原创文章,未经博主允许不得转载。

你可能感兴趣的:(Web,webservice,download,Services)