Devrath Devrath - 4 months ago 40
Android Question

OkHttp in android for making network requests

What i am trying to do::

I am trying to learn the usage of Okhttp for making networking calls in android




What i have done::


  • I have read their documentation here

  • I have downloaded and added the JAR in the project

  • I am using their sample code from here






MyCode::

MainActivity.java

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.internal.http.Request;
import com.squareup.okhttp.internal.http.Response;
public class MainActivity extends Activity {

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

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

Response response = client.execute(request);

Log.d("ANSWER", response.body().string());

}

}





Error i am facing::

In the line
Response response = client.execute(request);

I am getting error as :


client cannot resolved to a variable


How to resolve this !




{Update}



public class MainActivity extends Activity {

OkHttpClient client = new OkHttpClient();


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

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

Response response = client.execute(request);

Log.d("ANSWER", response.body().string());

}

}


Now i am facing error as :


in the line
Response response = client.execute(request);
as
The method execute(Request) is undefined for the type OkHttpClient


Answer

The method execute(Request) is undefined for the type OkHttpClient

You are getting this exception because there is no such method ie.execute(Request) for OkHttpClient. Rather it is invoked on Call object which is obtained using OkHttpClient object as follows:

  Call call = client.newCall(request);
  Response response = call.execute();

I think you should be using

Response response = client.newCall(request).execute();

instead of Response response = client.execute(request);

OkHttp docs

OkHttp Blog