1. Retrofit使用
Retrofit是一個現在網路請求框架,先來說一下怎么使用
- 網路權限(添加到AndroidManifest.xml)
<uses-permission android:name="android.permission.INTERNET" />
- gradle依賴(添加到build.gradle)
implementation("com.squareup.okhttp3:okhttp:4.9.2")
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
implementation 'com.squareup.retrofit2:converter-scalars:2.9.0'
- 定義介面,網路請求的方法
public interface Request {
@GET("/xx/xx")
Call<ResponseBody> get();
}
- 實體化Retrofit
Retrofit retrofit = new Retrofit.Builder().baseUrl("BASE_URL").build();
- 通過Retrofit實體創建介面服務物件
Request request = retrofit.create(Request.class);
- 呼叫介面中的方法
Call<ResponseBody> call = request.get();
- 執行異步請求(同步請求需要創建一個新的執行緒去執行)
call.enqueue(new retrofit2.Callback<ResponseBody>() {
@Override
public void onResponse(retrofit2.Call<ResponseBody> call, retrofit2.Response<ResponseBody> response) {
}
@Override
public void onFailure(retrofit2.Call<ResponseBody> call, Throwable t) {
}
});
2. Retrofit封裝
以上可以看出Retrofit是個好東西,可是用起來是比較麻煩的,所有在實際使用中對Retrofit進行一下小小的封裝是很有必要的,
- 定義介面(所有的請求引數都是以map的形式)
public interface Request {
/**
* 不帶引數的get請求
* @param url
* @return
*/
@GET()
Call<ResponseBody> get(@Url String url);
/**
* 帶引數的get請求
* @param url
* @param map 引數默認是map
* @return
*/
@GET()
Call<ResponseBody> get(@Url String url, @QueryMap Map<String,String> map);
/**
* 不帶引數的post請求
* @param url
* @return
*/
@POST()
Call<ResponseBody> post(@Url String url);
/**
* 帶引數的post請求
* @param url
* @param map
* @return
*/
@POST()
@FormUrlEncoded
Call<ResponseBody> post(@Url String url, @FieldMap Map<String,String> map);
}
- 定義RetrofitManager,以單例模式獲取Retrofit實體
public enum RetrofitManager {
/**
* RetrofitManager的實體
*/
INSTANCE;
/**
*
* 后端介面的baseUrl,且只考慮一個url的情況(ip+埠,或者域名)
*/
private static final String BASE_URL = " Your BASE_URL";
private Retrofit retrofit;
/**
* 回傳Retrofit實體,不添加轉換器
* @return
*/
public Retrofit getRetrofit(){
if(retrofit == null){
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.build();
}
return retrofit;
}
}
- 自定義的RetrofitCallback,在發送請求時,通過匿名物件作為引數獲取后端的回應結果,
public abstract class RetrofitCallback {
/**
* 開始執行的方法
*/
public void onStart(){
//開啟loading
}
/**
* 結束執行的方法
*/
public void onCompleted(){
//關閉loading
}
/**
* 執行成功
* @param resultJsonString 回傳的json字串
*/
public abstract void onSuccess(String resultJsonString);
/**
* 失敗
* @param t 例外
*/
public abstract void one rror(Throwable t);
/**
* 提示:服務例外
*/
public void serverErrMsg(){
//xxx
}
/**
* 提示:請求失敗
*/
public void reqErrMsg(){
//xxx
}
/**
* 提示:成功
*/
public void okMsg(){
//xxx
}
}
- 定義RetrofitUtil,封裝get和post方法,將RetrofitCallback作為請求引數,在發送請求時重寫onSuccess和onError方法,執行具體的操作,
public class RetrofitUtil {
private Retrofit(){}
/**
* 無參的get請求
* @param url
* @param callback
*/
public static void get(String url, RetrofitCallback callback){
sendRequest(getRequest().get(url),callback);
}
/**
* 有參的get請求
* @param url 請求的url
* @param map 引數
* @param callback 請求結束的回呼
*/
public static void get(String url, Map<String,String> map, RetrofitCallback callback){
sendRequest(getRequest().get(url,map),callback);
}
/**
* 無參的post請求
* @param url
* @param callback
*/
public static void post(String url, RetrofitCallback callback){
sendRequest(getRequest().post(url), callback);
}
/**
* 有參的post請求
* @param url
* @param map
* @param callback
*/
public static void post(String url, Map<String,String> map, RetrofitCallback callback){
sendRequest(getRequest().post(url,map), callback);
}
/**
* 獲取Request實體
* @return
*/
private static Request getRequest(){
Retrofit retrofit = RetrofitManager.INSTANCE.getRetrofit();
return retrofit.create(Request.class);
}
/**
* 發送請求的共通方法,并對回應結果進行處理
* @param call
* @param callback 自定義的Callback
*/
private void sendRequest(Call<ResponseBody> call,RetrofitCallback callback){
//開啟loading
callback.onStart();
//異步請求
call.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
//關閉loading
callback.onCompleted();
if(response.isSuccessful()){
//執行RetrofitCallback的onSuccess方法,獲取回應結果的json字串
try {
String result = response.body().string();
callback.onSuccess(result);
//回應成功
if(StringUtils.equals(result, Constant.SUCCESS)){
callback.okMsg();
}
} catch (IOException e) {
e.printStackTrace();
}
}else{
//服務例外
callback.serverErrMsg();
}
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
callback.onCompleted();
//請求失敗
callback.onError(t);
callback.reqErrMsg();
}
}
});
}
}
3. RetrofitUtil使用
get無參請求
RetrofitUtil.get("/xx/xx", new RetrofitCallback() {
@Override
public void onSuccess(String resultJsonString) {
}
@Override
public void one rror(Throwable t) {
}
});
get有參請求
Map<String,String> map = new HashMap<>(16);
map.put("key","value");
//xxx
RetrofitUtil.get("/xx/xx", map,new RetrofitCallback() {
@Override
public void onSuccess(String resultJsonString) {
xxxx
}
@Override
public void one rror(Throwable t) {
xxxx
}
});
post請求和get的使用方法相似
3. 最后
本次只對get和post進行了封裝,專案中只用到了這些就沒有對檔案上傳下載以及別的請求方式進行封裝,且沒有添加轉換器,可在RetrofitManager的getRetrofit()方法中自行添加,大概的封裝思路就是這樣的,可以自行發揮,
此文也只是在記錄專案中對Retrofit的使用,對Retrofit的原理并沒有較深的了解,
不足之處、歡迎留言,
感謝:對以下大佬的文章進行過參考,特此感謝
Android網路框架Retrofit2使用封裝:Get/Post/檔案上傳/下載
Retrofit的封裝
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/396691.html
標籤:其他
上一篇:android:自定義對話框
