前言
在使用Retrofit過程中,通過服務(wù)器獲取的數(shù)據(jù),不一定是標(biāo)準(zhǔn)的json數(shù)據(jù),當(dāng)時就想能不能有一種方式,可以把數(shù)據(jù)直接獲取到而不是解析好的數(shù)據(jù)
開始實現(xiàn)
主要是實現(xiàn)MediaType,以及responseBodyConverter和requestBodyConverter方法;
public class ToStringConverterFactory extends Converter.Factory {
private static final MediaType MEDIA_TYPE = MediaType.parse("text/plain");
@Override
public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) {
if (String.class.equals(type)) {
return new Converter<ResponseBody, String>() {
@Override
public String convert(ResponseBody value) throws IOException {
return value.string();
}
};
}
return null;
}
@Override public Converter<?, RequestBody> requestBodyConverter(Type type, Annotation[] parameterAnnotations,
Annotation[] methodAnnotations, Retrofit retrofit) {
if (String.class.equals(type)) {
return new Converter<String, RequestBody>() {
@Override
public RequestBody convert(String value) throws IOException {
return RequestBody.create(MEDIA_TYPE, value);
}
};
}
return null;
}
}
開始使用
public interface WechatService {
@GET("/txapi/weixin/wxhot") Call<String> getHotArticleStr(@Header("apikey") String apiKey,
@Query("num") int num, @Query("rand") int rand, @Query("word") String word, @Query("page") int page,
@Query("src") String src);
}
public void getHotArticleRxString(int num, int rand, String word, int page, String src) {
Retrofit retrofit = new Retrofit
.Builder()
.addConverterFactory(new ToStringConverterFactory())
.baseUrl(baseurl).build();
WechatService service = retrofit.create(WechatService.class);
Call<String> resultObser = service.getHotArticleStr(baiduApiKey, num, rand, word, page, src);
resultObser.enqueue(new Callback<String>() {
@Override public void onResponse(Call<String> call, Response<String> response) {
Log.e("jiangcy", "ToStringConverterFactory : " + response.body().toString());
}
@Override public void onFailure(Call<String> call, Throwable t) {
}
});
}