OkHttp gzip post body - android

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

Related

OKHTTP 3 MediaType as "application/x-www-form-urlencoded" crash issue

I was trying to implement postman's working as following for android app:
Here is my java codes:
MediaType CONTENT_TYPE = MediaType.parse("application/x-www-form-urlencoded");
RequestBody requestBody = new MultipartBody.Builder()
.setType(CONTENT_TYPE)
.addFormDataPart("phoneNumber", phone)
.addFormDataPart("serviceType", type)
.addFormDataPart("stripeToken", token)
.addFormDataPart("serviceCost", String.valueOf(amount))
.build();
final Request request = new Request.Builder()
.url(Const.URL_HEROKU_BASE+"payment/charge")
.post(requestBody)
.build();
It makes crash ...
I had the same issue when using the public api/login of this free rest service.
In postman, when passing body as application/x-www-form-urlencoded works. But in OkHttp3 MultipartBody doesn't work.
As #shindi suggested this code works perfectly for this api.
RequestBody requestBody = new FormBody.Builder()
.add("email", "some_email")
.add("password", "some_password")
.build();
.header() wasn't needed for the request either. Works for me. Hope it helps.
Change:
MultipartBody
to:
FormBody
I think you are not adding the content type properly:
Change this:
final Request request = new Request.Builder()
.url(Const.URL_HEROKU_BASE+"payment/charge")
.post(requestBody)
.build();
to:
final Request request = new Request.Builder()
.header("Content-Type", "application/x-www-form-urlencoded")
.url(Const.URL_HEROKU_BASE+"payment/charge")
.post(requestBody)
.build();
and remove the .setType(CONTENT_TYPE) part.
Let use FormBody as suggested at https://stackoverflow.com/a/53261129/2013887
And don't forget to use correct #RequestBody type, e.g MultiValueMap for application/x-www-form-urlencoded media type

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

404 error with POST and OkHttp3

I'm having an issue posting data to the Challonge API with OkHttp3 on Android... This is the jist of my code:
OkHttpClient client = new OkHttpClient();
HttpUrl.Builder urlBuilder = new HttpUrl.Builder();
urlBuilder = HttpUrl.parse("https://api.challonge.com/v1/tournaments/"+EVENT_ID+".json")
.newBuilder();
RequestBody postBody = new FormBody.Builder()
.add("_method", "post")
.add("api_key", API_KEY)
.add("participant[name]", name.getText().toString())
.add("participant[misc]", forum_id.getText().toString())
.build();
Request request = new Request.Builder()
.url(urlBuilder.build().toString())
.post(postBody)
.build();
Response response = client.newCall(request).execute();
No matter what I do, the resulting reponse is a 404 page.
If I do a GET response to the same URL, I get a proper response. However, the moment I add .post(postBody) to the request, its immediately 404s.
The documentation for the Challonge API is here:
http://api.challonge.com/v1/documents/participants/create
It looks to me like you're just using the wrong URL. The URL you've got there, "https://api.challonge.com/v1/tournaments/"+EVENT_ID+".json", is the URL for retrieving a single tournament, as seen here. This link was meant to receive GET requests.
According to the link you provided, you should alter your code to POST to https://api.challonge.com/v1/tournaments/"+EVENT_ID+"/participants.json

android okhttp post get "length required"message with 411 return code

I'm trying to use okhttp lib on my android app post PNG file to server.The server return 411 code ,the response message is "Length required".
My code :
RequestBody requestBody = new MultipartBuilder()
.type(MultipartBuilder.FORM)
.addPart(
Headers.of("Content-Disposition", "form-data; name=\"sendto\""),
RequestBody.create(null, sendtoJsonStr))
.addPart(
Headers.of("Content-Disposition", "form-data; name=\"picture\""),
RequestBody.create(MEDIA_TYPE_PNG, new File(filePath)))
.build();
long l = requestBody.contentLength();
Request request = new Request.Builder()
.url(url)
.post(requestBody)
.addHeader("Authorization","Token "+ UserLogin.getInstance().getLoginToken())
.build();
Response response = mClient.newCall(request).execute();
I have tried to use okhttp lib RequestBody class contentLength() function, but does't work.
Anyone can help me ? Thanks.
This problem is fixed in this issue and already merged into master. You can either wait for the 2.1 release of OkHttp or clone the repo and build the 2.1-SNAPSHOT JAR yourself.
EDIT: OkHttp 2.1 is out.

Categories

Resources