android – 改造OkHttp GZIP-ed JSON

前端之家收集整理的这篇文章主要介绍了android – 改造OkHttp GZIP-ed JSON前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我是Retrofit的新手,但它似乎非常强大.
使用普通的 JSON一切正常,但是当我尝试使用GZIP的时,我就会收到一个错误

I/System.out(14883): ——retrofit.RetrofitError:
retrofit.converter.ConversionException:
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException:
Expected BEGIN_OBJECT but was STRING at line 1 column 1

显然,我在Log中看到的乱码符号无法解析为JSON.

我认为okHttp是正确的gzip东西?
我错过了什么?

这些罐子在我的libs文件夹中:

retrofit-1.6.1.jar
okhttp-2.0.0.jar
gson-2.2.4.jar

这样我开始通话:

public interface OvlService {
    @GET("/gziptest.gz")
    void getOvls(Callback<OvlWrapper> callback);
}
...
OkHttpClient okHttpClient = new OkHttpClient();
Executor executor = Executors.newCachedThreadPool();
RestAdapter restAdapter = new RestAdapter.Builder()
.setEndpoint("http://my.domain") // The base API endpoint.
.setLogLevel(RestAdapter.LogLevel.FULL)
.setExecutors(executor,executor)
.setClient(new OkClient(okHttpClient))
.build();

OvlService ovlService = restAdapter.create(OvlService.class);

ovlService.getOvls(new Callback<OvlWrapper>() {

    @Override
    public void success(OvlWrapper arg0,Response arg1) {
        System.out.println("result: " + arg0.toString());
    }
});

结果:-line从未显示过,但我在RetrofitLog中看到了许多这些东西:T Mk A G 4. @ A .
gzip没有解压缩我怎么办?谢谢!

编辑:

我在我的测试服务器(server.com/ovl.gz)上使用gzip文件尝试了它,我也尝试使用原始的api服务器(server2.com/api.PHP?id=ovlgzip).结果相同,但标题不同:

测试服务器:

HTTP/1.1 200 OK
Accept-Ranges: bytes
Connection: close
Content-Length: 477
Content-Type: application/x-gzip
ETag: "2cc40cb-1dd-..."
Last-Modified: Tue,08 Jul 2014 17:00:08 GMT
OkHttp-Received-Millis: 1404950522590
OkHttp-Response-Source: NETWORK 200
OkHttp-Selected-Transport: http/1.1
OkHttp-Sent-Millis: 1404950522533
Server: Apache
�������������}�Qk�0���...

原始服务器:

HTTP/1.1 200 OK
Connection: Keep-Alive
Content-Type: application/json
Keep-Alive: timeout=4,max=1000
OkHttp-Received-Millis: 1404950697627
OkHttp-Response-Source: NETWORK 200
OkHttp-Selected-Transport: http/1.1
OkHttp-Sent-Millis: 1404950697002
Server: Apache
Transfer-Encoding: chunked
X-Powered-By: PHP/5.3.3-7+squeeze19
�������������}�Qk�0���...

解决方法

感谢 Jake Whartons comment,结果发现Content-Encoding:gzip标头丢失了.
因为我告诉服务器添加这些标题,一切正常:
<?PHP
$data = ...;
$gzdata = gzencode($data,9,FORCE_GZIP);
header('Content-Encoding: gzip');
header('Content-Length: '.strlen($gzdata));
... ?>
原文链接:https://www.f2er.com/android/318344.html

猜你在找的Android相关文章