-
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<String> call = test.getData(); //4.调用call方法,请求数据 call.enqueue(new Callback<String>() { @Override public void onResponse(Call<String> call, Response<String> response) { String body = response.body(); System.out.println("请求成功===="+body); } @Override public void onFailure(Call<String> call, Throwable throwable) { System.err.println("请求失败=====:"+throwable.getMessage()); } }
-
Retrofit学习笔记(一)
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
相关阅读更多精彩内容
- Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
