Retrofit学习笔记(一)

  • Retrofit 是什么

    • 项目地址: https://github.com/square/retrofit

    • 官方介绍: Type-safe HTTP client for Android and Java by Square(类型安全的HTTP客户端支持Android和Java)

    • 个人理解: 一个强大的第三方网络请求框架,可以通过注解配置请求,可以设置不同的HTTP客户端, 可以用不同的 Json Converter来序列化数据(Gson、FastJson等,如果不手动配置,默认只能接收字符串结果),经常和RxJava搭配使用。

    • 看图识字:

      retrofit流程架构
  • Retrofit 实现方法

    • 项目集成

      compile 'com.squareup.retrofit2:retrofit:2.1.0'//项目主包,必须导入
        
      compile 'com.squareup.retrofit2:adapter-rxjava:2.1.0'//和rxjava配合的包,选择性导入
      compile 'com.squareup.okhttp3:logging-interceptor:3.3.1'//okhttp,选择性导入
      compile 'com.squareup.retrofit2:converter-gson:2.1.0'//ConverterFactory的Gson依赖包,选择性导入
      
    • Hello world

        
      //1.创建对象
        Retrofit retorfit = new Retrofit.Builder()
          .baseUrl(httpUrl)//设置域名
          .client(client)//设置okhttp    
          .addCallAdapterFactory(RxJavaCallAdapterFactory.create())//设置适配工厂,这里使用了rxjava来适配
         .addConverterFactory(GsonConverterFactory.create())//设置转换工厂,这里使用Gson来做转换
          .build();//生成实例
      
      //2.获取api接口实现类的实例
         Test test = retrofit.create(Test.class);
      
      //3.调用接口获取Call对象
         Call call = test.getData();
      
      //4.调用call方法,请求数据
         call.enqueue(new Callback() {
        
             @Override
             public void onResponse(Call call, Response response) {
                 String body = response.body();
                 System.out.println("请求成功===="+body);
             }
         
             @Override
             public void onFailure(Call call, Throwable throwable) {
                 System.err.println("请求失败=====:"+throwable.getMessage());
             }
         }
            
      

你可能感兴趣的:(Retrofit学习笔记(一))