Java web services: sending files using the DataHandler class

I am new to Java web services, so I might be wrong.

I am trying to transfer a file using a DataHandler - this is what I have:

Web service:

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; } } 

Customer:

 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 } } } 

It seems like everything was done correctly, but the created file is empty - what am I doing wrong?

================== EDIT ===================

The DataHandler returned by getfile () is null - is it impossible to return this object from a web service?

+4
source share
1 answer

If the returned DataHandler is null , I think something will go wrong in this method (for example, the MalformedURLException that you are catching). If not, you can try to create a DataHandler differently, for example. with FileDataSource or ByteArrayDataSource .

+2
source

All Articles