Bana Bana - 5 months ago 49
Android Question

How to use OKHTTP in main java

This is a simple GET method in okhttp :

OkHttpClient client = new OkHttpClient();

String run(String url) throws IOException {
Request request = new Request.Builder()
.url(url)
.build();

Response response = client.newCall(request).execute();
return response.body().string();
}


I put this code in main java file.

So where should i call it into the onCreate method?

I don't know how can i use it. For example i want to use it in the onclicklistener of a button.

Answer

You have to download okHttp jar file and include it in your project if you are using eclipse or add the dependency in your build.gradle if you are using android studio. You can find the instructions here - http://square.github.io/okhttp/

It is better to create a common Util class for networking and write common methods HTTP requests (GET, POST etc) so that they can be called from anywhere within the application by just passing the parameters which are required.

Now if you want you can add it to on onclicklistener

Sample example -

public class GetExample {
OkHttpClient client = new OkHttpClient();

String run(String url) throws IOException {
Request request = new Request.Builder()
    .url(url)
    .build();

Response response = client.newCall(request).execute();
return response.body().string();
}

public static void main(String[] args) throws IOException {
GetExample example = new GetExample();
String response = example.run("https://raw.github.com/square/okhttp/master/README.md");
System.out.println(response);
}
}

For onClickListener you can write below code in AsyncTask or new Thread (I hope you know how to write AsyncTask or new Thread ) -

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

Response response = client.newCall(request).execute();
String reponse = response.body().string();