Retrofit 2.0接收字符串数据

Retrofit对RESTful API有很好的支持,使用了很多注解也让代码变得更加简洁。

Retrofit默认接收JSON格式的返回数据,可以使用GsonConverterFactory.create()对数据进行JSON转换。如果需要接收String类型的数据则需要自己实现Converter.Factory,下面是自己实现的对String类型数据的转换器

/**
 * Retrofit字符转换器
 * Created by 风雪涟漪 on 2015/11/4.
 */
public class StringConverterFactory extends Converter.Factory {

    private static final String TAG = "StringConverterFactory";

    public static StringConverterFactory create() {
        return new StringConverterFactory();
    }

    public StringConverterFactory() {
        super();
    }

    @Override
    public Converter<ResponseBody, ?> fromResponseBody(Type type, Annotation[] annotations) {
        // 由于Java没有标准的获取Type方法,借用GSON里的TypeToken来获取
        Type token = new TypeToken<String>(){}.getType();
        if (type == token) {
        // 目标类型为String类型则进行转换
            return new StringConverter();
        }
        return super.fromResponseBody(type, annotations);
    }

    @Override
    public Converter<?, RequestBody> toRequestBody(Type type, Annotation[] annotations) {
        return super.toRequestBody(type, annotations);
    }

    private class StringConverter implements Converter{

        @Override
        public Object convert(Object value) throws IOException {
            if (value != null) {
                if (value instanceof ResponseBody) {
                    ResponseBody rb = (ResponseBody) value;
                    return rb.string();
                }
            }
            return null;
        }
    }
}


在Retrofit 构建时添加转换器

Retrofit retrofit= new Retrofit.Builder()
        .baseUrl(host)
        .addConverterFactory(StringConverterFactory.create())// 先添加字符型的转换器,确定先对字符类型进行判断
        .addConverterFactory(GsonConverterFactory.create())
        .build();


然后对Service使用String类型

public interface AccountService {
    @GET("/account/login")
    Call<String> login(@Query("account") String account, @Query("password") String password);
}


那么在使用AccountService 的时候就能得到String类型的结果了

AccountService service = retrofit.create(AccountService.class);
Call<String> call = service.login(account,password);
String result = null;// String类型的数据结果
{
    result  = call.execute().body();
} (IOException e) {
    e.printStackTrace();
}


转载于:https://my.oschina.net/8048/blog/525998

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值