user8442466
user8442466

Reputation:

OkHttp on Android

This is my code to get the JSON string from my PHP server.

When I run this the app crashes and says that there is an error with Response response = client.newCall(request).execute(); What am I doing wrong?

public class MainActivity extends Activity {

    //private static final String TAG = "MainActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        new AsyncTask<Void, Void, String>(){

            @Override
            protected String doInBackground(Void... params) {

                OkHttpClient client = new OkHttpClient();
                Request request = new Request.Builder()
                        .url(url)
                        .build();

                try {
                    Response response = client.newCall(request).execute();
                    Log.d("OkHttp", "doInBackground() called with: " + "params = [" + response.body().string() + "]");
                    return response.body().string();
                } 
                catch (IOException e) {
                    e.printStackTrace();
                }
                return null;
            }
        }.execute();
    }
}

Upvotes: 1

Views: 956

Answers (1)

Aalap Patel
Aalap Patel

Reputation: 2076

  1. You don't need to put this into an async task as you can use the call back of the OKHttp library which itself is async.

  2. Second thing is you are using the wrong method. Instead of execute() you should use enqueue() which has a callback as a parameter as I mentioned above.

Try this code:

OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
                  .url(url)
                  .build();
Call call = client.newCall(request);
call.enqueue(new Callback() {

    @Override
    public void onFailure(Call call, IOException e) {

        // Observe reason of failure using
        e.printStackTrace();
    }

    @Override
    public void onResponse(Call call, Response response) throws IOException {
            if(response.isSuccessful()){
                // Use response here
            }
            else{
                // Observe error
            }
    }
});

Upvotes: 5

Related Questions