Java Web Services:使用DataHandler类发送文件

我是
Java Web Services的新手,所以我可能做错了.

我正在尝试使用DataHandler传输文件 – 这就是我所拥有的:

网络服务:

import java.net.MalformedURLException;
import java.net.URL;
import javax.activation.DataHandler;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebService;
import javax.xml.bind.annotation.XmlMimeType;

/**
 *
 * @author pc1
 */
@WebService()
public class WSFileSender {

    @WebMethod( operationName = "getfile" )
    public @XmlMimeType( "application/octet-stream" ) DataHandler getfile( @WebParam( name = "path" ) String path ) {

        DataHandler datahandler = null;

        try {
            datahandler = new DataHandler( new URL( path ) );
        }
        catch ( MalformedURLException e ) {
            System.out.println( "Bad" );
        }

        return datahandler;
    }

}

客户:

package fileclient;

import java.io.FileOutputStream;
import java.io.OutputStream;
import javax.activation.DataHandler;

/**
 *
 * @author pc1
 */
public class Main {

    /**
     * @param args the command line arguments
     */
    public static void main( String[] args ) {

        try {
            fspg.WSFileSenderService service = new fspg.WSFileSenderService();
            fspg.WSFileSender port = service.getWSFileSenderPort();

            DataHandler handler = port.getfile( "FileSender/file.jpg" );

            OutputStream out = new FileOutputStream( "dest.jpg" );

            handler.writeTo( out );

            out.close();

            System.out.println( "Done" );

        } catch (Exception ex) {
        // TODO handle custom exceptions here
    }

    }

}

似乎一切都正确完成,但创建的文件是空的 – 我做错了什么?

=================编辑==================

getfile()返回的DataHandler对象为null – 是否无法从Web服务返回此对象?

最佳答案 如果返回的DataHandler为null,我猜这个方法会出错(例如你正在捕获的MalformedURLException).如果没有,您可以尝试以不同的方式创建DataHandler,例如使用FileDataSource或ByteArrayDataSource.

点赞