How to make a POST REST call asynchronously in Java -
i have tried bunch of libraries make rest post
call using httpconnection
in java asynchronously. have tried many open source libraries , none of them seems serve purpose. there way in core java.
without knowing requirements or expectations:
here simple example without proper error handling shows how async http call can done using java 8
public static void main(string ... args) throws interruptedexception, executionexception, timeoutexception { future<object> futureresult = getobjectasync(); object value = futureresult.get(500, timeunit.milliseconds); } public static future<object> getobjectasync() { return completablefuture.supplyasync(() -> dohttpcall()); } static object dohttpcall() { try { httpurlconnection urlconnection = (httpurlconnection) new url("http://example.net/something").openconnection(); urlconnection.setrequestmethod("post"); try (outputstreamwriter out = new outputstreamwriter(urlconnection.getoutputstream())) { out.write("params json"); } try (inputstreamreader in = new inputstreamreader(urlconnection.getinputstream())) { // convert object return new object(); } } catch (ioexception e ) { throw new runtimeexception(e); } }
Comments
Post a Comment