1

In .Net if I want to upload a file asynchronously I just need to call the UploadFileAsync() instance method of the System.Net.WebClient class, block the main thread until it receives a signal from the waithandle I passed to the UploadFileAsync() method, and then inside an event handler procedure that is invoked once the file has been uploaded, signal the main thread using the same waithandle. The nice thing about uploading files this way is that it's also possible to subscribe an event handler procedure that is invoked each time there is a change in file upload progress.

In Java, is there a straightforward way to achieve similar functionality using the java.net.URLConnection class (or something similar)?

John Smith
  • 4,416
  • 7
  • 41
  • 56

2 Answers2

1

Yes, use ExecutorService and submit Callable object, then wait until future.get() returns with the result. For example:

ExecutorService executor = Executors.newSingleThreadExecutor();
Future<Foo> future = executor.submit(new Callable<Foo>()
{
    @Override
    public Foo call() throws Exception
    {
        // ...

        return someFoo;
    }
});

Foo result = future.get(); // result is the same as someFoo, both should refer to the same object

Note again that future.get() blocks until the background thread finishes executing call().

Eng.Fouad
  • 115,165
  • 71
  • 313
  • 417
  • but can ExecutorService be used to receive file upload progress? – John Smith Feb 14 '13 at 00:36
  • Yes, put your code inside `call()` and it will be executed in a background thread. You should receive the result through `future.get()`. – Eng.Fouad Feb 14 '13 at 00:40
  • That's not what he's talking about. He means like periodic progress reports: "Your file upload is 10% complete ... 20% ... 30% ..." – Ryan Stewart Feb 14 '13 at 00:42
  • @RyanStewart Ah I see. Anyway, you could also print the progress from within `call()` or update some variables without any problems. But in case of GUI application (Swing), use `SwingWorker`. See [this answer for more details on how SwingWorker works](http://stackoverflow.com/a/11546203/597657). – Eng.Fouad Feb 14 '13 at 00:45
  • Obviously you could do that. It's also a lot of work, and it seems like something pretty common that should already be provided by some existing library. – Ryan Stewart Feb 14 '13 at 00:47
0

There appears to be an async version of the excellent Apache Http Client. I haven't used it myself, but it looks promising.

The Jersey client also has async request support built in that might meet your needs. There's a test class for it that demonstrates its use.

The Jersey client, at least, offers callbacks for request completion, but I'm not sure about the progress callbacks for file uploads.

Ryan Stewart
  • 126,015
  • 21
  • 180
  • 199