Retrofit+okhttp3, encapsulate network request framework

One: Know Retrofit and okhttp3

Retrofit is a network request framework developed and designed by square

Official Website: Retrofit

Okhttp is a network request library developed and designed by square. The request/response API adopts a smooth builder and immutability design. It supports both synchronous blocking calls and asynchronous calls with callbacks

Official Website: Overview - OkHttp

This blog is the basic article of network requests, use Retrofit as the carrier of network requests and responses, understand the annotations of Retrofit, the role of Okhttp is to filter logs, and improve network requests (such as timeout processing, request body processing, etc.)

The method of use is as follows:

in app\build.gradle

1: Depend on the Maven library

dependencies {
    //retrofit2 okhttp3
    implementation "com.squareup.retrofit2:retrofit:2.9.0"
    implementation "com.squareup.retrofit2:converter-gson:2.9.0"
    implementation "com.squareup.okhttp3:logging-interceptor:4.7.2"
}

2: jar package dependencies

     Download from the official website

Two: Preparation

Free Json data interface:

1: Construct the Retrofit object

        //构造retrofit,返回请求接口
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(baseUrl)
                .addConverterFactory(GsonConverterFactory.create())
                .client(builder.build())
                .build();
        service =  retrofit.create(BaseService.class);

2: Add okhttp log filter

        //构造okhttp3,日志过滤
        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(HttpLoggingInterceptor.Logger.DEFAULT);
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        if(BuildConfig.DEBUG){
            builder.addInterceptor(interceptor);
        }

3: Build CallBack

    //构建Callback
    public void callEnqueue(Call<T> call,BaseListener<T> listener){
        call.enqueue(new Callback<T>() {
            @Override
            public void onResponse(@NonNull Call<T> call, @NonNull Response<T> response) {
                if(response.isSuccessful()){
                    listener.onResponse(response.body());
                }else{
                    listener.onFail(response.message());
                }
            }

            @Override
            public void onFailure(@NonNull Call<T> call, @NonNull Throwable t) {
                listener.onFail(t.getMessage());
            }
        });
    }

4: Improve the Service request interface and understand the functions of each annotation

//Method annotation: @GET @POST @PUT @DELETE @PATH @HEAD @OPTIONS @HTTP 
// 
//Mark annotation: @FormUrlEncoded @Multipart @Streaming 
// 
//Parameter annotation: @Query @QueryMap @Body @Field @ FieldMap @Part @PartMap 
// 
//Other annotations: @Path @Header @Headers @Url

 Take GET/POST/ including request headers, path parameters, request parameters, Json data, and file parameters as an example

    //路径参数
    @GET("posts/{postId}/comments")
    Call<List<CommentsBean>> getComments(
            @Path("postId") int postId
    );

    @GET("photos")
    Call<List<PhotoBean>> getPhoto(
            @Query("id") int id
    );

    //请求参数
    @GET("users")
    Call<List<UserBean>> getUser(
            @Query("id") int id);

    //Post请求
    @POST("todos")
    Call<TodoBean>postTodo();

    //包含请求头的POST请求
    @Headers("Content-Type:application/x-www-form-urlencoded")
    @POST("api/sdk/stat/v1/launch/{gameId}/{channelId}")
    Call<StatsBean>postLaunchGame(
          @Path("gameId") String gameId,
          @Path("channelId") String channelId,
          @Body RequestBody responseBody
    );

    //包含json的POST请求
    //上传跑步数据
    @FormUrlEncoded
    @POST("Record/uploadRunningRecord")
    Call<BaseBean> uploadRunningRecord(@Field("Json") String route);

    //上传跑步地图截屏
    @Multipart
    @POST("Record/uploadRunningImage")
    Call<BaseBean> uploadRunningImage(@Part MultipartBody.Part file,
                                      @Query("sessionId") String sessionId,
                                      @Query("studentId") String studentId);

5: Initiate a request and call an instance

    private void getPhoto(ImageView imageView) {
        ProgressDialog dialog = new ProgressDialog(this);
        dialog.setMessage("正在加载中...");
        dialog.show();
        BaseModel<List<PhotoBean>> model = new BaseModel<>();
        Call<List<PhotoBean>> call = model.service.getPhoto(3);
        model.callEnqueue(call, new BaseListener<List<PhotoBean>>() {
            @Override
            public void onResponse(List<PhotoBean> bean) {
                dialog.dismiss();
                Glide.with(MainActivity.this).load(bean.get(0).getUrl())
                        .placeholder(R.drawable.ic_launcher_background)
                        .into(imageView);
            }

            @Override
            public void onFail(String e) {
                dialog.dismiss();
                Log.d(TAG, "getPhoto onFail:" + e);
            }
        });
    }

Retrofit 's onResponse and onFail are on the main thread, thread switching has been completed, and UI operations can be performed.

This is the difference with Okhttp .

6: Rendering

Attach the complete demo:

GitHub - sunbofly23/JavaRetrofitOkhttp: retrofit+okhttp, Android network request framework

 Three: Summary

The simple use of Retrofit+okhttp for replaying network requests, as far as we know, the latest technology

Retrofit+okhttp+moshi+kotlin coroutine

The network request framework that can be implemented is more scalable and robust. Still have to learn later.

Guess you like

Origin blog.csdn.net/qq_34123324/article/details/131402016