如何在Java中异步进行POST REST调用

时间:2017-04-07 02:57:12

标签: java

我尝试了一堆库,以异步方式在Java中使用REST POST进行HttpConnection调用。我尝试了很多开源库,似乎没有一个能满足我的需求。有没有办法在核心Java中执行此操作。

1 个答案:

答案 0 :(得分:2)

不知道您的要求或期望:

这是一个没有正确错误处理的简单示例,它显示了如何使用Java 8完成异步HTTP调用

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 as json");
        }

        try (InputStreamReader in = new InputStreamReader(urlConnection.getInputStream())) {
            // convert to Object
            return new Object();
        }

    } catch (IOException e ) {
        throw new RuntimeException(e);
    }
}