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();
}