Retrofit 自定義Converter.Factory實現(xiàn)直接接收String

前言

在使用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) {

            }
        });
    }

demo 地址

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容