当前位置:   article > 正文

Retrofit+okhttp3使用,附带源码解析_retrofit ok

retrofit ok

一:认识Retrofit和okhttp3

Retrofit是由square 开发设计的 网络请求框架

官方网址:Retrofit

Okhttp 是由square 开发设计的 网络请求库,请求/响应API采用流畅的构建器和不变性设计。它同时支持同步阻塞调用和带有回调的异步调用

官方网址:Overview - OkHttp

这篇博客是网络请求的基础篇,使用Retrofit作为网络请求及响应的载体,了解Retrofit的注解,Okhttp的作用在于日志过滤,以及完善网络请求(比如超时处理,请求体处理等)

使用方法如下:

在app\build.gradle

1:依赖Maven库

  1. dependencies {
  2. //retrofit2 okhttp3
  3. implementation "com.squareup.retrofit2:retrofit:2.9.0"
  4. implementation "com.squareup.retrofit2:converter-gson:2.9.0"
  5. implementation "com.squareup.okhttp3:logging-interceptor:4.7.2"
  6. }

2:jar包依赖

     在官网下载

二:准备工作

免费的Json数据接口 :

1:构造Retrofit对象

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

2:添加okhttp日志过滤器

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

3:构建CallBack

  1. //构建Callback
  2. public void callEnqueue(Call<T> call,BaseListener<T> listener){
  3. call.enqueue(new Callback<T>() {
  4. @Override
  5. public void onResponse(@NonNull Call<T> call, @NonNull Response<T> response) {
  6. if(response.isSuccessful()){
  7. listener.onResponse(response.body());
  8. }else{
  9. listener.onFail(response.message());
  10. }
  11. }
  12. @Override
  13. public void onFailure(@NonNull Call<T> call, @NonNull Throwable t) {
  14. listener.onFail(t.getMessage());
  15. }
  16. });
  17. }

4:完善Service请求接口,了解各注解作用

//方法注解:@GET  @POST  @PUT  @DELETE  @PATH  @HEAD  @OPTIONS  @HTTP
//
//标记注解:@FormUrlEncoded  @Multipart   @Streaming
//
//参数注解:@Query  @QueryMap  @Body  @Field  @FieldMap  @Part  @PartMap
//
//其他注解:@Path  @Header  @Headers  @Url

 以GET/POST/包含请求头Headers,路径参数,请求参数,Json数据,文件参数为例

  1. //路径参数
  2. @GET("posts/{postId}/comments")
  3. Call<List<CommentsBean>> getComments(
  4. @Path("postId") int postId
  5. );
  6. @GET("photos")
  7. Call<List<PhotoBean>> getPhoto(
  8. @Query("id") int id
  9. );
  10. //请求参数
  11. @GET("users")
  12. Call<List<UserBean>> getUser(
  13. @Query("id") int id);
  14. //Post请求
  15. @POST("todos")
  16. Call<TodoBean>postTodo();
  17. //包含请求头的POST请求
  18. @Headers("Content-Type:application/x-www-form-urlencoded")
  19. @POST("api/sdk/stat/v1/launch/{gameId}/{channelId}")
  20. Call<StatsBean>postLaunchGame(
  21. @Path("gameId") String gameId,
  22. @Path("channelId") String channelId,
  23. @Body RequestBody responseBody
  24. );
  25. //包含json的POST请求
  26. //上传跑步数据
  27. @FormUrlEncoded
  28. @POST("Record/uploadRunningRecord")
  29. Call<BaseBean> uploadRunningRecord(@Field("Json") String route);
  30. //上传跑步地图截屏
  31. @Multipart
  32. @POST("Record/uploadRunningImage")
  33. Call<BaseBean> uploadRunningImage(@Part MultipartBody.Part file,
  34. @Query("sessionId") String sessionId,
  35. @Query("studentId") String studentId);

5:发起请求,调用实例

  1. private void getPhoto(ImageView imageView) {
  2. ProgressDialog dialog = new ProgressDialog(this);
  3. dialog.setMessage("正在加载中...");
  4. dialog.show();
  5. BaseModel<List<PhotoBean>> model = new BaseModel<>();
  6. Call<List<PhotoBean>> call = model.service.getPhoto(3);
  7. model.callEnqueue(call, new BaseListener<List<PhotoBean>>() {
  8. @Override
  9. public void onResponse(List<PhotoBean> bean) {
  10. dialog.dismiss();
  11. Glide.with(MainActivity.this).load(bean.get(0).getUrl())
  12. .placeholder(R.drawable.ic_launcher_background)
  13. .into(imageView);
  14. }
  15. @Override
  16. public void onFail(String e) {
  17. dialog.dismiss();
  18. Log.d(TAG, "getPhoto onFail:" + e);
  19. }
  20. });
  21. }

RetrofitonResponseonFail是在主线程的,已经完成了线程切换,可以进行UI操作。

这是与Okhttp的区别。

6:效果图

附上完整demo:

GitHub - sunbofly23/JavaRetrofitOkhttp: retrofit+okhttp,安卓网络请求框架

三:从源码分析:

基于retrofit:2.9.0

下面简单梳理了一下retrofit 使用的技术点

retrofit:构建者设计模式,工厂模式,反射,动态代理,类加载器,注解

这里先过一遍retrofit从构建,到与okhttp转换的流程:

Retrofit.

->create(Retrofit.java)

->invokeHandle(Retrofit.java)

->loadServiceMethod-一层缓存(serviceMethodCache)(ServiceMethod.java)

->createCallAdapter(HttpServiceMethod.java)

->createResponseConverter(HttpServiceMethod.java)

->invoke(HttpServiceMethod.java)

->构造OkHttpCall并且adapt(call) 这一步结束,就是将Call交给okhttp发起请求

->get(CallAdapter<R, T> .Factory.java)

->DefaultCallAdapterFactory(DefaultCallAdapterFactory extends CallAdapter.Factory)

->ExecutorCallbackCall(DefaultCallAdapterFactory.java)这一步完成线程的切换

->CompletableFutureCallAdapterFactory(CompletableFutureCallAdapterFactory extends CallAdapter.Factory)

->retrun future(CompletableFuture)

然后从Retrofit.create开始分析 

->loadServiceMethod

 ->createCallAdapter、createResponseConverter

 ->invoke

 ->DefaultCallAdapterFactory

 ->ExecutorCallbackCall

 这里就会将请求 进队列交给okhttp3

 ->CompletableFutureCallAdapterFactory

 ->retrun future/callback.onResponse解析response.body()

四:总结

复盘网路请求Retrofit+okhttp的简单使用,据了解,最新技术

Retrofit+okhttp+moshi+kotlin协程

可实现的网络请求框架更易扩展,健壮。后续还要学习。

本文内容由网友自发贡献,转载请注明出处:https://www.wpsshop.cn/w/Guff_9hys/article/detail/1021617
推荐阅读
相关标签
  

闽ICP备14008679号