我们一般为了方便解析数据,会在配置Retrofit时设置数据转为实体Bean
new Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create())// Gson转换器
...
但是如果我们在测试阶段,或不知道返回内容时,需要得到返回的String类型数据,该怎么做呢?
下面提供两种方法:
1.更换转换器为Scalars
//依赖
compile com.squareup.retrofit2:converter-scalars:2.0.0'
// 配置
new Retrofit.Builder()
.addConverterFactory(ScalarsConverterFactory.create())
...
// 将返回类型修改为String
public interface ApiInterfacr {
@POST(Api.GetCarBrand)
Observable<String> getBrand();
}
ApiInterfacr apiInterfacr = retrofit.create(ApiInterfacr.class);
Observable<String> observable = apiInterfacr.getBrand();
......
.subscribe(new Observer<String>() {
......
@Override
public void onNext(String result)
mResponseText.setText(result());
}
......
});
2.不用换转换器,修改Call<ResponseBody>类型必须是ResponseBody
public interface ApiInterfacr {
@POST(Api.GetCarBrand)
Observable<ResponseBody> getBrand();
}
ApiInterfacr apiInterfacr = retrofit.create(ApiInterfacr.class);
Observable<ResponseBody> observable = apiInterfacr.getBrand();
......
.subscribe(new Observer<ResponseBody>() {
......
@Override
public void onNext(ResponseBody result) {
try {
mResponseText.setText(result.string());
} catch (IOException e) {
e.printStackTrace();
}
}
......
});
3.没有第三种啦