I have been looking at the examples in OkHttp for Android and I notice there are two methods defined, one is called "run" and the other "post" but they never seem to be called. Is something responsible for calling these? How are they called?
Or are these just standard methods, shown as an example that I can change?
Here is a snippet from the example, obviously I don't understand it fully as they look like "stray" methods, nobody is calling them.
Here is the "run":
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();
}
And the other snippet here is the "post", I don't see any reference to it:
public static final MediaType JSON
= MediaType.parse("application/json; charset=utf-8");
OkHttpClient client = new OkHttpClient();
String post(String url, String json) throws IOException {
RequestBody body = RequestBody.create(JSON, json);
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
Response response = client.newCall(request).execute();
return response.body().string();
}
What is the reasoning behind it?
These are the methods, which will perform the request on the given URL.
You just need to call them like this:
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();
}
String response = run("http://www.url.com");
Also, you can change their name, to anything. It doesn't matter.
The most important part of this code is:
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(url)
.build();
Response response = client.newCall(request).execute();
And you can play with the response
object for getting the responseCode
, responseBody
, Headers
etc.