天天看點

OkHttp處理從背景得到的Response将其轉為對應的JavaBean

emmm 。。。

当你用OkHttp去请求后台的数据,后台给你返回了一个Json,OkHttp拿到这个Response,然后开开心心的 response.body().toStirng() 得到了数据,去用Gson转,但却转不出来!

你用JsonObject、Gson都处理不了这个Response,比如明明用返回的数据去 JSON-Handle 做了解析是可以出来的,而我在强转的时候却转不出这个类呢?

这很有可能是后台没有对输出的数据进行 序列化或者格式上 的处理。所以我们要自己对这个数据进行处理啦(能和后台沟通好就好啦,但是他们一般都会叫你自己处理…)

对没错,我们要二次处理response这些字符,考虑它的编码格式…

(一般都是编码格式的问题,因为后台用的是linux,android 一般是Win/Linux,不同的操作系统支持的编码格式肯定是不同的。

private String getResponseString(Response response) {
        String res = "";
        ResponseBody responseBody = response.body();
        long contentLength = responseBody.contentLength();
        if (!bodyEncoded(response.headers())) {
            BufferedSource source = responseBody.source();
            try {
                source.request(Long.MAX_VALUE); // Buffer the entire body.
            } catch (IOException e) {
                e.printStackTrace();
            }
            Buffer buffer = source.buffer();

            Charset charset = Charset.forName("UTF-8");
            MediaType contentType = responseBody.contentType();
            if (contentType != null) {
                try {
                    charset = contentType.charset(Charset.forName("UTF-8"));
                } catch (UnsupportedCharsetException e) {
                    LogUtil.e(TAG, e.getMessage());
                    e.printStackTrace();
                }
            }

            if (contentLength != 0) {
                res = buffer.clone().readString(charset);
            }
        }
        return res;
    }
    
    private boolean bodyEncoded(Headers headers) {
        String contentEncoding = headers.get("Content-Encoding");
        return contentEncoding != null && !contentEncoding.equalsIgnoreCase("identity");
    }