一. 如何发送一个纯文本作为请求体
方法一:使用 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);
}