OkHttp returning unreadable characters - android

I am sending a request to server and getting Collection + Json in responce. Every thing is perfect in PostMan.
But when I am doing same things in code using OKHTTP, I am getting some unreadable characters.
Here is my code
OkHttpClient client = new OkHttpClient();
requestBody = new FormBody.Builder()
.add("email", email)
.add("password", psd)
.build();
Request request = new Request.Builder()
.url(url)
.addHeader("Accept", "application/vnd.collection+json")
.addHeader("Accept-Encoding", "gzip")
.addHeader("Authorization", "Basic YWRtaW46cmVhbHNlYw==")
.post(requestBody)
.build();
try {
Response response = client.newCall(request).execute();
String s = response.body().string();
response.body().close();
} catch (Exception e) {
e.printStackTrace();
}
I tried some other url and those are working perfect.
many thanks.

Finally I solved the issue and it wasn't very difficult one although I tried lot's of difficult approaches :P
I solved the issue by removing this line from the code
.addHeader("Accept-Encoding", "gzip")
hope it help to some one other who got stuck like me.
Thanks

Related

OkHttp bad requestBody

I am using OkHTTP and I have some problems when I try to make a post request.
Here is my code :
client = new OkHttpClient();
formBody = new FormBody.Builder()
.add(Constant.DIRECTION, Constant.OUT)
.add(Constant.LIMIT, Constant.docs_limit)
.add(Constant.IMPORTED, Constant.FALSE)
.addEncoded("statuses[]", "4")
request = new Request.Builder()
.url(url)
.addHeader(Constant.AUTH_TOKEN, sharedPreferences.getString(Constant.TOKEN, ""))
.post(formBody)
.build();
when I try to send
"statuses[]", "4"
in the debugger it shows that brackets converted to "statuses%5B%5D".
How to fix that? Sorry for my poor english.

OkHTTP how to replace team_number from url POST

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();

Issue in POST method with Woocommerce REST API

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.

Appending a param value to a url while making network request in android using okhttp

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/

OkHttp gzip post body

I am trying to migrate my Android project to OkHttp.
What I am wondering is if OkHttp will compress the body of my POST requests with gzip?
I am using it like this (from the example on the home page):
RequestBody body = RequestBody.create(JSON, json);
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
Will this RequestBody actually gzip the json if it's "big enough", or do I need to do this manually? Like I did before with AndroidHttpClient like this:
AndroidHttpClient.getCompressedEntity(json, context.getContentResolver())
If I need to do it manually, what is the best approach?
Thank you!
According to GitHub issues for OkHttp, we should do it manually:
https://github.com/square/okhttp/issues/350
"For the time being your best option is to do it manually: compress the content and add Content-Encoding: gzip."
This is how I'm doing it now:
byte[] data = json.getBytes("UTF-8");
ByteArrayOutputStream arr = new ByteArrayOutputStream();
OutputStream zipper = new GZIPOutputStream(arr);
zipper.write(data);
zipper.close();
RequestBody body = RequestBody.create(JSON, arr.toByteArray());
Request request = new Request.Builder()
.url(url)
.post(body)
.header("Content-Encoding", "gzip")
.build();
I took the code from the AndroidHttpClient from here, and just using it inline without the ByteArrayEntity:
http://grepcode.com/file/repo1.maven.org/maven2/org.robolectric/android-all/4.2.2_r1.2-robolectric-0/android/net/http/AndroidHttpClient.java#AndroidHttpClient.getCompressedEntity%28byte%5B%5D%2Candroid.content.ContentResolver%29
Knowing it's too late to answer but if anyone might need it in future.
A newer and easier way to do this is by following
val request = Request.Builder().url("…")\ .addHeader("Content-Encoding", "gzip")\ .post(uncompressedBody.gzip())\ .build()
More details can be found here

Categories

Resources