mahdi
mahdi

Reputation: 942

encoding of response http response body

I'm using okhttp library for sending request to rest api. this is my java code for sending request to https:

RequestBody body = RequestBody.create(JSON, requestBody);

    Request request = new Request.Builder().url("https://examplesite.com/json/").post(body)
            .addHeader("Accept", "application/json, text/javascript, */*; q=0.01")
            .addHeader("Accept-Encoding", "gzip").addHeader("Accept-Language", "en-US,en;q=0.8,fa;q=0.6,ar;q=0.4")
            .build();

    Response response = client.newCall(request).execute();
    String res = new String(response.body().string().getBytes("UTF-8"));

    System.out.println(res);

the res variable is: �CU8{$���'L�@R�W*�$��b�H�E�l�K�C� 30��}c&,p��q���)+3�R�28���#SC�

what is the encoding of above text?

this is response header:

Accept:application/json, text/javascript, */*; q=0.01
Accept-Encoding:gzip, deflate
Accept-Language:en-US,en;q=0.8,fa;q=0.6,ar;q=0.4
Connection:keep-alive
Content-Length:95
Content-Type:application/json

I can't understand what is the encoding of the response body. whatever when I send request by postman extension on chrome that response body is a normal json. attend that the protocol is https and I think okhttp library handle encrypting and decripting data.

Upvotes: 7

Views: 8816

Answers (2)

HaKu
HaKu

Reputation: 41

String commentUri = "http://comment.bilibili.com/4.xml";

    Log.d("request_comment url", commentUri);
    Request requestComment = new Request.Builder()
            .addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8")
//                .addHeader("Accept-Encoding", "gzip, deflate")
            .addHeader("Connection", "keep-alive")
            .addHeader("Accept", "*/*")
            .url(commentUri)
            .build();

I meet the same problem, I used okhttp 3.2.0 like this,but still cannot unpack defalte, it returns like this : U��n�0E���k{���4v|]W�vۑ⸊��8

delete add header accept-encoding didn't help

Upvotes: 2

Jesse Wilson
Jesse Wilson

Reputation: 40593

Remove this:

 .addHeader("Accept-Encoding", "gzip")

When you do this, you’re telling OkHttp that you want to manage your own response compression.

If you don’t explicitly configure the Accept-Encoding, OkHttp will take care of you. It’ll add the header to the request, and decompress the response.

Upvotes: 13

Related Questions