Retrofit 的使用
来源:互联网 发布:linux 定时唤醒 编辑:程序博客网 时间:2024/05/17 21:04
Retrofit
一、概述
Retrofit是Square公司开发的一个类型安全的Java和Android 的HTTP客户端库。
A type-safe HTTP client for Android and Java.
二、简单使用
- 采用豆瓣电影TOP250的API
1. 添加 gradle
依赖
- 通过
Android Studio
-File
-Project Structure
-app
-Dependencies
-“+”
-Library Dependency
里搜索添加 - 通过到官网查询最新依赖,并在
build.gradle
里添加
compile 'com.squareup.retrofit2:retrofit:2.2.0'compile 'com.google.code.gson:gson:2.8.0'compile 'com.squareup.retrofit2:converter-gson:2.2.0'
2. 在 AndroidManifest.xml
里加入网络访问权限
<uses-permission android:name="android.permission.INTERNET"/>
3. 创建 MovieEntity
实体类,解析服务器返回的 JSON
数据
- 建议使用
Gson
解析,使用GsonFormat
或GsonOrXmlFormat
插件一键生成
// 代码不贴了
4. 创建一个Java接口 ApiService
来作为HTTP请求接口
public interface ApiService { @GET("top250") Call<MovieEntity> getTopMovies(@Query("start") int start, @Query("count") int count); }
5. 实例化 Retrofit
,并通过 Retrofit
对象实现上面的接口
String baseUrl = "https://api.douban.com/v2/movie/";Retrofit retrofit = new Retrofit .Builder() .baseUrl(baseUrl) .addConverterFactory(GsonConverterFactory.create()) .build();ApiService apiService = retrofit.create(ApiService.class);
6. 通过接口发起请求
- 同步调用
MovieEntity movieEntity = call.execute();
- 异步调用
Call<MovieEntity> call = apiService.getTopMovies(0,10);call.enqueue(new Callback<MovieEntity>() { @Override public void onResponse(Call<MovieEntity> call, Response<MovieEntity> response) { // 处理请求返回的数据 } @Override public void onFailure(Call<MovieEntity> call, Throwable t) { // 请求错误处理 }});
7. 取消请求,即使是正在执行的请求,也能够立即终止。
call.cancel();
- 效果图
源码:https://github.com/bazhancong/SimpleRetrofitDemo
参考:
RxJava 与 Retrofit 结合的最佳实践
Retrofit官网
0 0
- Retrofit 的使用
- retrofit 的使用。
- Retrofit 的使用简介
- Retrofit的使用封装
- retrofit的使用
- Retrofit的简单使用
- retrofit的使用
- Retrofit的简单使用
- Retrofit的简单使用
- Retrofit + RxAndroid的使用
- Retrofit框架的使用
- Retrofit+RxJava的使用
- Retrofit的初步使用
- Retrofit的使用
- Retrofit 初步的使用
- Retrofit的使用
- Retrofit的简单使用
- Retrofit的使用笔记
- C++单利模式
- 山区修路
- GreenDao 3.1 应用
- Extreme (II)
- java中的接口(interface)
- Retrofit 的使用
- CODEVS 1166 矩阵取数游戏
- qscoj 66 ||2017 UESTC Training for Data Structures D(离线+树状数组)
- 算法设计Week9 LeetCode Algorithms Problem #121. Best Time to Buy and Sell Stock
- [leetcode]: 476. Number Complement
- HDOJ 3045 Picnic Cows(斜率优化DP)
- 原生ajax
- Android 画画板
- Maven实战之Web项目部署