Retrofit2 学习笔记(二)

一. 如何发送一个纯文本作为请求体

方法一:使用 Scalars Converter

Scalars Converter 可以用于序列化的 text/plain 请求

compile  'com.squareup.retrofit2:converter-scalars:2.1.0'  
Retrofit retrofit = new Retrofit.Builder()  
        .addConverterFactory(ScalarsConverterFactory.create())
        .addConverterFactory(GsonConverterFactory.create())
        .baseUrl("https://your.base.url/")
        .build();
public interface ScalarService {  
    @POST("path")
    Call<String> getStringScalar(@Body String body);
}
String body = "plain text request body";  
Call<String> call = service.getStringScalar(body);

Response<String> response = call.execute();  
String value = response.body();  
方法二:使用 ResponseBody 类
public interface ScalarService {  
    @POST("path")
    Call<ResponseBody> getStringRequestBody(@Body RequestBody body);
}
String text = "plain text request body";  
RequestBody body =  
        RequestBody.create(MediaType.parse("text/plain"), text);

Call<ResponseBody> call = service.getStringRequestBody(body);  
Response<ResponseBody> response = call.execute();  
String value = response.body().string();  

二. 失败重连

使用call.clone().eqnqueue(),同时可以控制 retry number


public abstract class CallbackWithRetry<T> implements Callback<T> {

    private static final int TOTAL_RETRIES = 3;
    private static final String TAG = CallbackWithRetry.class.getSimpleName();
    private final Call<T> call;
    private int retryCount = 0;

    public CallbackWithRetry(Call<T> call) {
        this.call = call;
    }

    @Override
    public void onFailure(Throwable t) {
        Log.e(TAG, t.getLocalizedMessage());
        if (retryCount++ < TOTAL_RETRIES) {
            Log.v(TAG, "Retrying... (" + retryCount + " out of " + TOTAL_RETRIES + ")");
            retry();
        }
    }

    private void retry() {
        call.clone().enqueue(this);
    }
}

serviceCall.enqueue(new CallbackWithRetry<List<Album>>(serviceCall) {
    @Override
    public void onResponse(Response<List<Album>> response) {
        ...
    }
});

或者

public abstract class BackoffCallback<T> implements Callback<T> {
    private static final int RETRY_COUNT = 3;
    /**
     * Base retry delay for exponential backoff, in Milliseconds
     */
    private static final double RETRY_DELAY = 300;
    private int retryCount = 0;

    @Override
    public void onFailure(final Call<T> call, Throwable t) {
        retryCount++;
        if (retryCount <= RETRY_COUNT) {
            int expDelay = (int) (RETRY_DELAY * Math.pow(2, Math.max(0, retryCount - 1)));
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    retry(call);
                }
            }, expDelay);
        } else {
            onFailedAfterRetry(t);
        }
    }

    private void retry(Call<T> call) {
        call.clone().enqueue(this);
    }

    public abstract void onFailedAfterRetry(Throwable t);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值