Search code examples
androidgetokhttp

How to save result from a GET request with OkHttp in a local variable?


I'm trying to make a Get Request with OkHttp in Java. I made it successfully using asynchronous threads but I'm "stuck" Inside onResponse function. I mean, I can't use the result of the request anywhere else than in this function. How can I do to make this code work ?

            OkHttpClient client = new OkHttpClient();

            Request request = new Request.Builder()
                    .url("https://raw.github.com/square/okhttp/master/README.md")
                    .build();

            client.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    e.printStackTrace();
                }

                @Override
                public void onResponse(Call call, final Response response) throws IOException {
                        final String responseData = response.body().string();
                    LoginInscription.this.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            TextView tv = findViewById(R.id.txtString);
                            tv.setText(responseData);
                        }
                    });
                }
            });

            TextView tv = findViewById(R.id.txtString);
            String res = tv.getText().toString();

            System.out.println(res);

Thanks...


Solution

  • I am sure your System.out.println(res); might not work as scope of final String res ends before this.

    You can declare a activity/class level variable/method which can be updated onResponse(). For ex:

    @Override
    public void onResponse(Call call, Response response) throws IOException {
    
        final String myResponse = response.body().string();
        MainActivity.this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                txtString.setText(myResponse);
            }   
        });
    }
    

    Get more examples at: https://www.journaldev.com/13629/okhttp-android-example-tutorial