Android retrofit2几种请求方式的使用以及简单封装

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/Mr___Xu/article/details/94596187

1添加依赖.

annotationProcessor 'com.jakewharton:butterknife-compiler:8.8.1'
implementation 'com.squareup.okhttp3:logging-interceptor:3.4.1'
implementation 'com.squareup.okhttp3:okhttp:3.4.1'
implementation 'com.squareup.retrofit2:retrofit:2.2.0'
implementation 'com.squareup.retrofit2:converter-gson:2.2.0'
implementation 'com.squareup.retrofit2:converter-scalars:2.2.0'
implementation 'com.squareup.retrofit2:adapter-rxjava:2.2.0'

2.RetrofitManager

public class RetrofitManager {
    private static final String TAG = "RetrofitManager";
    private static RetrofitManager mRetrofitManager;
    private Retrofit mRetrofit;
    private RequestServes apiService;

    public static RetrofitManager getInstance() {
        if (mRetrofitManager == null) {
            synchronized (RetrofitManager.class) {
                if (mRetrofitManager == null) {
                    mRetrofitManager = new RetrofitManager();
                }
            }
        }
        return mRetrofitManager;
    }


    private RetrofitManager() {
        initRetrofit();
    }

    public void initRetrofit() {
        HttpLoggingInterceptor logging = new HttpLoggingInterceptor();//添加访问网络的日志
        logging.setLevel(HttpLoggingInterceptor.Level.BODY);//日志级别
        /*
         **打印retrofit信息部分
         */
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
            @Override
            public void log(String message) {
                //打印retrofit日志
                Log.e("RetrofitLog", "retrofitBack = " + message);
            }
        });
        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        OkHttpClient client = new OkHttpClient.Builder()//okhttp设置部分,此处还可再设置网络参数
                .addInterceptor(new Interceptor() {
                    @Override
                    public Response intercept(Chain chain) throws IOException {
                        Request request = chain.request()
                                .newBuilder()
                                .addHeader("access_token", SharedPreferencesUtil.get(applicationContext, "token", "") + "")
                                .build();
                        return chain.proceed(request);
                    }
                })
                .addInterceptor(loggingInterceptor)
                .build();

        Log.e(TAG, "initRetrofit: ");
        mRetrofit = new Retrofit.Builder()
                .baseUrl(BaseUtil.HOST)
                .client(client)
                .addConverterFactory(ScalarsConverterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .build();
        Log.e(TAG, "initRetrofit: " + mRetrofit);

        apiService = mRetrofit.create(RequestServes.class);

    }


    public RequestServes getService() {
        Log.e(TAG, "getService: " + apiService);
        return apiService;
    }

    public static RequestBody getBody(HashMap map) {
        Gson gson = new Gson();
        String strEntity = gson.toJson(map);
        Log.e("=====json串", strEntity);
        RequestBody body = RequestBody.create(okhttp3.MediaType.parse("application/json;charset=UTF-8"), strEntity);
        return body;
    }}

3.RequestServes接口

public interface RequestServes {
@POST("communal/order")//post请求提交json
Call<CreateOrderBean> postPay(@Body RequestBody route);
@FormUrlEncoded
@POST("property/houseuserrelation/add")//post请求提交表单
Call<HttpResultBean<LoginResultBean>> addPayAddress(@Field("userId") String userId, @Field("houseId") String houseId);


@PUT("property/userCommunity/modifyUserCommunity")//put请求提交json
Call<String> putModify(@Body RequestBody route);
@DELETE("property/houseuserrelation/delete")//delete请求提交表单
Call<HttpResultBean<LoginResultBean>> deleteHouse(@Query("id") String id);
@GET("property/userCommunity/getUserCommunity/{userId}")//get请求直接拼"/"加参数
Call<HttpResultBean<CommunityChaBean>> getUserCommunity(@Path("userId") String userId);
@GET("property/house/selectBuildingById")//get请求
Call<HttpResultArrayBean<ChooseBuildingBean>> getHouse(@Query("id") String id);
}

4.HttpResultArrayBean

public class HttpResultArrayBean<T> {

    private int statusCode;
    @SerializedName(value = "message", alternate = "msg")
    private String msg;
    private List<T> items;

    public int getStatusCode() {
        return statusCode;
    }

    public void setStatusCode(int statusCode) {
        this.statusCode = statusCode;
    }

    public String getMsg() {
        return msg == null ? "" : msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public List<T> getItems() {
        if (items == null) {
            return new ArrayList<>();
        }
        return items;
    }

    public void setItems(List<T> items) {
        this.items = items;
    }
}

5.HttpResultBean

public class HttpResultBean<T> {

    private int statusCode;
    @SerializedName(value = "message", alternate = "msg")
    private String msg;
    private T items;

    public int getStatusCode() {
        return statusCode;
    }

    public void setStatusCode(int statusCode) {
        this.statusCode = statusCode;
    }

    public String getMsg() {
        return msg == null ? "" : msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public T getItems() {
        return items;
    }

    public void setItems(T items) {
        this.items = items;
    }


    public HttpResultBean toResponse() {
        HttpResultBean httpResultBean = new HttpResultBean();
        httpResultBean.setStatusCode(statusCode);
        httpResultBean.setMsg(msg);
        return httpResultBean;
    }
}

6.BaseUtil

public class BaseUtil {
        public static final String HOST = "http://";}

7.应用

RetrofitManager.getInstance().getService().postPay(body).enqueue(new Callback<String>() {
    @Override
    public void onResponse(Call<String> call, Response<String> response) {
        if (response.isSuccessful()) {
           
        }
    }

    @Override
    public void onFailure(Call<String> call, Throwable t) {

    }
});
//    //缓存路径
//    File cacheFile = new File(Environment.getExternalStorageDirectory(), "HttpCache");
//    Cache cache = new Cache(cacheFile, 1024 * 1024 * 10);//缓存文件为100MB
//        Log.e(TAG, "initRetrofit: " + cacheFile.getAbsolutePath());
//
//    HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
//        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
//
//    OkHttpClient httpClient = new OkHttpClient.Builder()
//            .addInterceptor(new Interceptor() {
//                @Override
//                public Response intercept(Chain chain) throws IOException {
//                    Request request = chain.request()
//                            .newBuilder()
////                                .addHeader("TSQ-RequestId", BaseUtil.encryptByPublicKey())
//                            .build();
//                    return chain.proceed(request);
//                }
//            })
//            .connectTimeout(5, TimeUnit.SECONDS)//设置连接超时
//            .readTimeout(10, TimeUnit.SECONDS)//读取超时
//            .writeTimeout(10, TimeUnit.SECONDS)//写入超时
//            .addInterceptor(interceptor)//添加日志拦截器
////                .addNetworkInterceptor(REWRITE_CACHE_CONTROL_INTERCEPTOR)//添加缓存拦截器
//            .cache(cache)//把缓存添加进来
//            .build();

猜你喜欢

转载自blog.csdn.net/Mr___Xu/article/details/94596187