Retrofit and OkHttp gzip decode

匿名 (未验证) 提交于 2019-12-03 01:59:02

问题:

The REST service I want to consume answers as a gzipped encoded JSON. It provides the Content-Encoding: gzip, but my OkHttp does not encode it to readable text, so the JSON converter throws an exception.

According to Jake Whartons comment the Content-Encoding: gzip Header should tell OkHttp to decode the body.

The code for creating the RestAdapter is:

final RestAdapter adapter = new RestAdapter.Builder()     .setEndpoint(baseUrl)     .setClient(new OkClient(new OkHttpClient()))     .setConverter(new GsonConverter(gson))     .setLogLevel(RestAdapter.LogLevel.FULL)     .build(); service = adapter.create(RaplaService.class); 

The gradle dependencies are:

compile 'com.squareup.retrofit:retrofit:1.9.0' compile 'com.squareup.okhttp:okhttp:2.6.0' 

The method in my ServiceInterface:

@Headers({         "Accept-Encoding: gzip, deflate",         "Content-Type: application/json;charset=utf-8",         "Accept: application/json" }) @GET("/events") List getEvents(@Header("Authorization") String token, @Query("resources") String resources, @Query("start") String start, @Query("end") String end); 

回答1:

Replace this:

@Headers({     "Accept-Encoding: gzip, deflate",     "Content-Type: application/json;charset=utf-8",     "Accept: application/json" }) 

With this:

@Headers({     "Content-Type: application/json;charset=utf-8",     "Accept: application/json" }) 

When you provide your own Accept-Encoding header you’re instructing OkHttp that you want to do your own decompression. By omitting it, OkHttp will take care of both adding the header and the decompression.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!