|
package com.jiangtj.utils; |
|
|
|
import lombok.extern.slf4j.Slf4j; |
|
import retrofit2.Call; |
|
import retrofit2.Callback; |
|
import retrofit2.Response; |
|
|
|
import java.io.IOException; |
|
import java.util.Optional; |
|
import java.util.function.Consumer; |
|
|
|
/** |
|
* Created by MrTT (jiang.taojie@foxmail.com) |
|
* 2019/9/5. |
|
*/ |
|
@Slf4j |
|
public class RetrofitUtils { |
|
|
|
public static <T> Optional<T> execute(Call<T> call) { |
|
T object = null; |
|
try { |
|
Response<T> response = call.execute(); |
|
if (response.isSuccessful()) { |
|
object = response.body(); |
|
} else { |
|
log.error("RetrofitUtils execute fail code:{} errorBody:{}", response.code(), response.errorBody().string()); |
|
} |
|
} catch (IOException e) { |
|
log.error("RetrofitUtils IOException:", e); |
|
} |
|
return Optional.ofNullable(object); |
|
} |
|
|
|
public static <T> void execute(Call<T> call, Consumer<T> success) { |
|
execute(call, success, throwable -> log.error("RetrofitUtils onFailure:", throwable)); |
|
} |
|
|
|
public static <T> void execute(Call<T> call, Consumer<T> success, Consumer<Throwable> fail) { |
|
call.enqueue(new Callback<T>() { |
|
@Override |
|
public void onResponse(Call<T> call, Response<T> response) { |
|
if (response.isSuccessful()) { |
|
success.accept(response.body()); |
|
} else { |
|
try { |
|
log.error("RetrofitUtils execute fail code:{} errorBody:{}", response.code(), response.errorBody().string()); |
|
} catch (IOException e) { |
|
log.error("RetrofitUtils IOException:", e); |
|
} |
|
} |
|
} |
|
@Override |
|
public void onFailure(Call<T> call, Throwable throwable) { |
|
fail.accept(throwable); |
|
} |
|
}); |
|
} |
|
|
|
} |