I have been looking at the examples in OkHttp for android and I notice there are 2 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();
}
Can anyone explain the reasonning behind it ?
thanks.
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.
Related
I am creating Requestbody, adding necessary paramters to it and requesting POST method of OKHTTP.
But, Is there any way to pass the whole JsonObject instead of putting seperate parameters to Object of RequestBody ?
Thanks.
for that you have to build your jsonObject and pass that jsonObject as rawString in POST method.
Note : "Google how to pass rawString in POST methode android"
To send JSON Object request we need to create RequestBody Object and Pass it into Request Object. In the RequestBody object, we have to pass Media type and post data as a string.
public static final MediaType MEDIA_TYPE = MediaType.parse("application/json");
JSONObject postdata = new JSONObject();
try {
postdata.put("UserName", "Vishal");
postdata.put("Email", "vishal#####gmail.com");
} catch(JSONException e){
// TODO Auto-generated catch block
e.printStackTrace();
}
RequestBody body = RequestBody.create(MEDIA_TYPE, postdata.toString());
final Request request = new Request.Builder()
.url("YOUR URL")
.post(body)
.addHeader("Content-Type", "application/json")
.addHeader("Authorization", "Your Token")
.addHeader("cache-control", "no-cache")
.build();
Hope this will help you.
Try This
OkHttpClient client = new OkHttpClient();
RequestBody formBody = new FormBody.Builder()
.add("message", "Your message")
.build();
Request request = new Request.Builder()
.url("http://www.foo.bar/index.php")
.post(formBody)
.build();
try {
Response response = client.newCall(request).execute();
// Do something with the response.
} catch (IOException e) {
e.printStackTrace();
}
I have url like this.
http://host/parallel/team/:team_number.json
and it has post params.
like team_number, team_name.
How to make a post request such that i replace team_number to team number with a value.
Does :team_number need to be handled differently ?
So far i have done
RequestBody formBody = new FormBody.Builder()
.addEncoded(TEAM_NUMBER,tracking_number)
.add(TRACK_NAME, name)
.build();
Request request = new Request.Builder()
.url(SEND_TRACKING_DATA)
.post(formBody)
.build();
Response response = CoreApplication.okHttpClient.newCall(request).execute();
return response.body().string();
I'm developing an android app with Woocommerce REST API.
I 'm able to access the data's through this REST api using GET method,
now i'm facing issue in creating new customer using this REST API.
here POST method is not working.
my END_POINT is "http:example.com/wp-json/wc/v1/customers"
the problem is am getting authentication error.
I'm using OkHttp for network call.
Here is my code:
protected String doInBackground(Void... params) {
try {
MediaType JSON = MediaType.parse("application/json; charset=utf-8");
String authHeader = Credentials.basic(Config.CONSUMER_KEY, Config.CONSUMER_SECRET);
Log.e(TAG, "doInBackground: auth -> " + authHeader);
RequestBody body = RequestBody.create(JSON, json);
Request request = new Request.Builder()
.url(url)
.post(body)
.addHeader("Content-Type", "application/json; charset=utf-8")
.addHeader("Accept", "application/json")
.addHeader("Authorization", authHeader)
.build();
OkHttpOAuthConsumer consumer = new OkHttpOAuthConsumer(Config.CONSUMER_KEY, Config.CONSUMER_SECRET);
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(new SigningInterceptor(consumer))
.build();
Response response = client.newCall(request).execute();
return response.message();
} catch (IOException e) {
e.printStackTrace();
Log.e(TAG, "doInBackground: " + e.getLocalizedMessage());
return Tag.IO_EXCEPTION;
}
}
Response message is :
{"code":"woocommerce_rest_cannot_create","message":"Sorry, you are not allowed to create resources.","data":{"status":401}}
i don't know where is an issue is.
If anyone experienced this problem, means please share your solution.
Thanks in advance.
I'm just learning Retrofit and OKHttp, now I have an issue.
Every request in my app is POST, just like this:
#FormUrlEncoded
#POST("some url")
Observable<Result> getData(#Field("id") String id);
In every POST, there are two same params. So in a most simple way, I can add two more #Field in every method, for example, #Field("token"),#Field("account"). But I think there must be a smart way.
Then I thought OkHttpClient may solve this.
OkHttpClient client = new OkHttpClient.Builder().addInterceptor(new Interceptor() {
#Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
RequestBody body = new FormBody.Builder().add("account", "me")
.add("token", "123456").build();
request = request.newBuilder().post(body).build();
return chain.proceed(request);
}
}).build();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("some base url")
.client(client)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.build();
Or
HttpUrl url = request.url().newBuilder()
.setEncodedQueryParameter("account", "me")
.setEncodedQueryParameter("token", "123456")
.build();
The first method just replace all Field to these two.
The second method just add these two as GET parameters, not POST.
Now I have absolutely no idea how to make this work.
OK...Finally I find a way to do this. But I'm not sure this is the best way.
Here is the code:
OkHttpClient client = new OkHttpClient.Builder().addInterceptor(new Interceptor() {
#Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
FormBody.Builder bodyBuilder = new FormBody.Builder();
FormBody b = (FormBody) request.body();
for (int i=0;i<b.size();i++) {
bodyBuilder.addEncoded(b.name(i),b.value(i));
}
bodyBuilder.addEncoded("account", "me").add("token", "123456");
request = request.newBuilder().post(bodyBuilder.build()).build();
return chain.proceed(request);
}
}).build();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://some url)
.client(client)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.build();
I get all the #Field from retrofit, then add every key-value params to a new RequestBody, same as these two default params. Now every POST request has "account" and "token".
If there is a better way to do this, please let me know.
You can do that by adding a new request interceptor to the OkHttpClient. Intercept the actual request and get the HttpUrl. The http url is required to add query parameters since it will change the previously generated request url by appending the query parameter name and its value.
OkHttpClient.Builder httpClient =
new OkHttpClient.Builder();
httpClient.addInterceptor(new Interceptor() {
#Override
public Response intercept(Chain chain) throws IOException {
Request original = chain.request();
HttpUrl originalHttpUrl = original.url();
HttpUrl url = originalHttpUrl.newBuilder()
.addQueryParameter("apikey", "your-actual-api-key")
.build();
// Request customization: add request headers
Request.Builder requestBuilder = original.newBuilder()
.url(url);
Request request = requestBuilder.build();
return chain.proceed(request);
}
});
What I was doing:
I was using android http library to make http requests
What i am doing:
I have migrated into Oktttp now and i am using below code
In doInBackground of an AsyncTask i am calling the below function
public static String getRequestNoPayload(String urlString) throws Exception {
client.setConnectTimeout(20, TimeUnit.SECONDS); // connect timeout
client.setReadTimeout(20, TimeUnit.SECONDS); // socket timeout
Request request = new Request.Builder()
.url(urlString)
.addHeader("phonenumber",AppController.getPhoneNumber())
.addHeader("authtoken",AppController.getAuthCode())
.build();
Response response = client.newCall(request).execute();
return response.body().string();
}
value of url:
String urlString=Keys.login_api+"?phonenumber="+edtPhnoId.getText().toString().trim();
What is happening:
Not able to send requests like this since i am appending the url with
a param ?
How to resolve this ... should i go for any specific encoding
methods, if so which is that one
Any sample would help
Try this
RequestBody formBody = new FormEncodingBuilder()
.add("search", "Jurassic Park")
.build();
Request request = new Request.Builder()
.url("https://en.wikipedia.org/w/index.php")
.post(formBody)
.build();
Response response = client.newCall(request).execute();
https://publicobject.com/2014/06/12/okhttp-ate-mimecraft/