6

I've created a web service in Java that returns a DataHandler. This has to be able to return a File, which works fine. But it should also be able to return a String. Any idea how I can transfer a String with a DataHandler?

dumazy
  • 13,857
  • 12
  • 66
  • 113

1 Answers1

11

JavaMail has a ByteArrayDataSource that you can use for this purpose:

DataSource ds = new ByteArrayDataSource(theString, "text/plain; charset=UTF-8");
DataHandler handler = new DataHandler(ds);

The charset in the mime type determines what encoding it will use to convert the string to bytes.

Ian Roberts
  • 120,891
  • 16
  • 170
  • 183
  • Thanks, this helped me out when I tried it in a new project for testing. But when I implement it in my current project and try to run it I'm getting a 'WebServiceException: failed to access the WSDL'. I don't have this error if I send a file with a FileDataSource... – dumazy Mar 05 '13 at 12:16
  • After further testing and logging: the ByteArrayDataSource constructor causes my webMethod to be called again (once) and does nothing... It doesn't even throw an exception of any kind – dumazy Mar 05 '13 at 14:26