There is such a code

import java.io.IOException; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; public class FetchJson { public String getJsonString(String url) throws IOException{ OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder() .url(url) .build(); Response response = client.newCall(request).execute(); String result = response.body().string(); return result; } } 

How do I pass to the getJsonString method the method that I need to call and pass the result of the request on completion?

    1 answer 1

    Make an interface:

     interface MyCallback { void call(String result); } 

    Pass it as a parameter:

     public void getJsonString(String url, MyCallback callback) throws IOException { OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder() .url(url) .build(); Response response = client.newCall(request).execute(); String result = response.body().string(); callback.call(result); } 

    When calling, implement the interface method:

     FetchJson fetchJson = new FetchJson(); try { fetchJson.getJsonString("http://example.com", new MyCallback() { @Override public void call(String result) { // тут получаем наш результат } }); } catch (IOException e) { e.printStackTrace(); // etc }