Skip to content

Instantly share code, notes, and snippets.

@swankjesse
Created August 19, 2019 14:25
Show Gist options
  • Save swankjesse/3c11c407f2fc80c1fa9242a94dd0f7e2 to your computer and use it in GitHub Desktop.
Save swankjesse/3c11c407f2fc80c1fa9242a94dd0f7e2 to your computer and use it in GitHub Desktop.
/*
* Copyright (C) 2014 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.io.IOException;
import java.util.concurrent.CompletableFuture;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public final class CompletableFutureGet {
private final OkHttpClient client = new OkHttpClient();
public void run() throws Exception {
Request request = new Request.Builder()
.url("http://publicobject.com/helloworld.txt")
.build();
CompletableFuture<Response> future = new CompletableFuture<>();
client.newCall(request).enqueue(toCallback(future));
Response response = future.get();
System.out.println(response.body().string());
}
public Callback toCallback(CompletableFuture<Response> future) {
return new Callback() {
@Override public void onFailure(Call call, IOException e) {
future.completeExceptionally(e);
}
@Override public void onResponse(Call call, Response response) {
future.complete(response);
}
};
}
public static void main(String... args) throws Exception {
new CompletableFutureGet().run();
}
}
@EhsanSetayesh
Copy link

hello swankjesse ....
thanks for your gist.
please help me ...
i want to use completableFuture to run network call with okhttpclient ..
and i want to do this in for loop so i have a list that for each item i want to call network request and handle each responses ...
i know i can do it with rx and other ways but in this project i have to use okhhtpclient to make network call
please help me

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment