美文网首页
Retrofit框架学习

Retrofit框架学习

作者: Sincerity_ | 来源:发表于2019-05-30 10:27 被阅读0次

1. Retrofit基本使用

  1. 注解的分类:

    1. http请求方法的8种注解: get,post,put delete,head,patch,options和hettp
    2. 标记类: FormUrlEncoded ,Multipart,Streaming
    3. 参数类:header,body,path,filed,fieldMap,part,partMap,query,queryMap
    4. @query参数:http://102.10.10.132/api/News?newsId=1&type=类型1
    5. @query参数:http://102.10.10.132/api/News?newsId=1&type=类型1
    6. @Url参数 :把URl当做参数传递过来
    7. @Body参数以json形式传递过来.
    8. @Part 上传单个文件
    9. get/pos请求网络
    10. post请求:http://102.10.10.132/api/Comments/1?access_token=1234123
      @FormUrlEncoded
         @POST("Comments/{newsId}")
         Call<Comment> reportComment(
             @Path("newsId") String commentId,//@Path所有在网址中的参数(URL的问号前面)没有key
             @Query("access_token") String access_token,//@Query:URL问号后面的参数 有key
             @Field("reason") String reason); //@Field:用于POST请求,提交单个数据 使用@Field时记得添加@FormUrlEncoded
     //  reason 是补全的url  post的数据只有一条reason 
    
  2. 网络请求

    Retrofit retrofit = new Retrofit.Builder() //注释1
    //                .baseUrl("https://www.baidu.com/")
                    .baseUrl("http://fanyi.youdao.com/")
                    .addConverterFactory(GsonConverterFactory.create())
                    .build(); //注释2
            API api = retrofit.create(API.class);// 注释3 创建动态代理模式
            Call<TransitionMode> call = api.acquisitionOfTranslationContent("car");
            call.enqueue(new Callback() { //注释4
                @Override
                public void onResponse(Call call, Response response) {
                    Log.e("TAg", response.body().toString());
                }
    
                @Override
                public void onFailure(Call call, Throwable t) {
                    Log.e("Tag", t.getMessage());
                }
            });
    
  3. 源码解析:

    1. 注释1:Retrofit retrofit = new Retrofit.Builder() //注释1

      private static Platform findPlatform() {
          try {
            Class.forName("android.os.Build"); //判断是否是android平台
            if (Build.VERSION.SDK_INT != 0) {
              return new Android();
            }
          } catch (ClassNotFoundException ignored) {
          }
          try {
            Class.forName("java.util.Optional"); //是否是jdk8 Retrofit支持lamuda表达式
            return new Java8();
          } catch (ClassNotFoundException ignored) {
          }
          return new Platform();
        //  目前版本去除了对IOS平台的判断
        }
      //判断不同平台,从而调用不同的线程池,
      
      /*--------------------------------Android----------------------------------*/
       static class Android extends Platform {
          @Override public Executor defaultCallbackExecutor() {
            return new MainThreadExecutor();
          }
      
          @Override CallAdapter.Factory defaultCallAdapterFactory(@Nullable Executor callbackExecutor) {
            if (callbackExecutor == null) throw new AssertionError();
            return new ExecutorCallAdapterFactory(callbackExecutor); 
          }
      
          static class MainThreadExecutor implements Executor {
            private final Handler handler = new Handler(Looper.getMainLooper());
      
            @Override public void execute(Runnable r) {
              handler.post(r);//将线程切换到主线程
            }
          }
        } 
      /*--------------------------------JAVA8----------------------------------*/
      //JAVA8  仅仅在java8上运行
      static class Java8 extends Platform {
          @Override boolean isDefaultMethod(Method method) {
            return method.isDefault(); //
          }
      
          @Override Object invokeDefaultMethod(Method method, Class<?> declaringClass, Object object,
              @Nullable Object... args) throws Throwable {
            // Because the service interface might not be public, we need to use a MethodHandle lookup
            // that ignores the visibility of the declaringClass.
            Constructor<Lookup> constructor = Lookup.class.getDeclaredConstructor(Class.class, int.class);
            constructor.setAccessible(true);
            return constructor.newInstance(declaringClass, -1 /* trusted */)
                .unreflectSpecial(method, declaringClass)
                .bindTo(object)
                .invokeWithArguments(args);
          }
        }
      
    2. 注释2 retrofit.build

      public Retrofit build() {
            if (baseUrl == null) {
              throw new IllegalStateException("Base URL required."); //如果url为空,抛出异常
            }
      
            okhttp3.Call.Factory callFactory = this.callFactory;
            if (callFactory == null) {
              callFactory = new OkHttpClient(); //构造默认的网络请求工厂
            }
            //MainThreadExecutor默认的构造器, 默认返回的是android平台
            Executor callbackExecutor = this.callbackExecutor;
            if (callbackExecutor == null) {
              callbackExecutor = platform.defaultCallbackExecutor(); //构造默认方法回调执行器
            }
      
            //添加默认适配器工厂ExecutorCallAdapterFactory,
            List<CallAdapter.Factory> callAdapterFactories = new ArrayList<>(this.callAdapterFactories);
            callAdapterFactories.add(platform.defaultCallAdapterFactory(callbackExecutor));
      
            //创建默认的数据转换器工厂,
            List<Converter.Factory> converterFactories =
                new ArrayList<>(1 + this.converterFactories.size());
                //首先添加内置转换器
            converterFactories.add(new BuiltInConverters());
            converterFactories.addAll(this.converterFactories);
      
            return new Retrofit(callFactory, baseUrl, unmodifiableList(converterFactories),
                unmodifiableList(callAdapterFactories), callbackExecutor, validateEagerly);
          }
      
    3. 注释3API api = retrofit.create(API.class);

      {
          Utils.validateServiceInterface(service); //判断传递过来的参数是否是interface
          if (validateEagerly) {
            eagerlyValidateMethods(service);
          }
          return (T) Proxy.newProxyInstance(service.getClassLoader(), new Class<?>[] { service },
              new InvocationHandler() {
                private final Platform platform = Platform.get();
      
                @Override public Object invoke(Object proxy, Method method, @Nullable Object[] args)
                    throws Throwable {
                  // If the method is a method from Object then defer to normal invocation.
                  if (method.getDeclaringClass() == Object.class) {
                    return method.invoke(this, args);
                  }
                  if (platform.isDefaultMethod(method)) {
                    return platform.invokeDefaultMethod(method, service, proxy, args);
                  }
                  ServiceMethod<Object, Object> serviceMethod =
                      (ServiceMethod<Object, Object>) loadServiceMethod(method);
                  OkHttpCall<Object> okHttpCall = new OkHttpCall<>(serviceMethod, args);
                  return serviceMethod.adapt(okHttpCall);
                }
              });
        }
      
      

相关文章

网友评论

      本文标题:Retrofit框架学习

      本文链接:https://www.haomeiwen.com/subject/ybkmtctx.html