关闭

retrofit2.0转换String 报错修复

1814人阅读 评论(1) 收藏 举报
分类:

添加Gson转换支持

new Retrofit.Builder()
                    .addConverterFactory(GsonConverterFactory.create())
                    .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                    .baseUrl(AppVars.RequestPath.BASE_URL)
                    .client(App.getOkHttpClient())
                    .build();

然后这样设置后 Call< String>会出现gson类型转换异常

需要添加字符串转换


import com.squareup.okhttp.ResponseBody;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Type;
import java.lang.annotation.Annotation;

import retrofit.Converter;

/**
 * retrofit转换成字符串支持
 * Created by Administrator on 2015/11/19.
 */
public final class StringConverterFactory extends Converter.Factory {
    public static StringConverterFactory create() {
        return new StringConverterFactory();
    }

    @Override
    public Converter<ResponseBody, ?> fromResponseBody(Type type, Annotation[] annotations) {
        return new ConfigurationServiceConverter();
    }

    final class ConfigurationServiceConverter implements Converter<ResponseBody, String> {

        @Override
        public String convert(ResponseBody value) throws IOException {
            BufferedReader r = new BufferedReader(new InputStreamReader(value.byteStream()));
            StringBuilder total = new StringBuilder();
            String line;
            while ((line = r.readLine()) != null) {
                total.append(line);
            }
            return total.toString();
        }
    }
}

最后添加

 retrofit = new Retrofit.Builder().addConverterFactory(StringConverterFactory.create())
                    .addConverterFactory(GsonConverterFactory.create())
                    .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                    .baseUrl(AppVars.RequestPath.BASE_URL)
                    .client(App.getOkHttpClient())
                    .build();
0
1

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:34104次
    • 积分:668
    • 等级:
    • 排名:千里之外
    • 原创:24篇
    • 转载:9篇
    • 译文:1篇
    • 评论:10条
    文章分类
    最新评论