Reputation: 4516
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)?
Upvotes: 1
Views: 203
Reputation: 117589
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()
.
Upvotes: 1
Reputation: 128799
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.
Upvotes: 0