Retrofit2简单使用
2018-09-21 本文已影响10人
Ello_Orld
1. Gradle配置
implementation 'com.squareup.retrofit2:retrofit:2.4.0'
implementation 'com.squareup.retrofit2:converter-gson:2.4.0'
2. 基本的get请求
我们使用GankApi 来进行测试。
如: 获取闲读的主分类 https://gank.io/api/xiandu/categories
获取结果如下:
{
"error":false,
"results":[
{
"_id":"57c83777421aa97cbd81c74d",
"en_name":"wow",
"name":"科技资讯",
"rank":1
},
{
"_id":"57c83577421aa97cb162d8b1",
"en_name":"apps",
"name":"趣味软件/游戏",
"rank":5
},
.....
]
}
a. 编写实体类 Categorise.java
这个可以用一些工具自动生成实体类。不需要get、set
/**
* Auto-generated: 2018-09-19 22:43:15
*
* @author bejson.com (i@bejson.com)
* @website http://www.bejson.com/java2pojo/
*/
public class Categories {
private boolean error;
private List<Results> results;
public class Results {
private String _id;
private String en_name;
private String name;
private int rank;
@Override
public String toString() {
return "Results{" +
"_id='" + _id + '\'' +
", en_name='" + en_name + '\'' +
", name='" + name + '\'' +
", rank=" + rank +
'}';
}
}
@Override
public String toString() {
return "Categories{" +
"error=" + error +
", results=" + results +
'}';
}
}
b. 定义一个接口对象GankApi.java
public interface GankApi {
//完整url: https://gank.io/api/xiandu/categories ,https://gank.io/api/作为baseUrl
@Get("xiandu/categories")
Call<Categories> getCategories();
}
c. 创建retrofit并进行数据请求
NetWork.java
public class NetWork{
private static GankApi sGankApi;
public static final String BASE_URL = "https://gank.io/api/";
private static GankApi getGankApi() {
if (sGankApi == null) {
sGankApi = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build().create(GankApi.class);
}
return sGankApi;
}
//异步操作方式
public static void getGankCategories(ResultCallback<Categories> resultCallback){
Call<Categories> gankCategories = getGankApi().getGankCategories();
gankCategories.enqueue(new Callback<Categories>() {
@Override
public void onResponse(Call<Categories> call, Response<Categories> response) {
Categories body = response.body();
if (body == null) {
resultCallback.onError("body is null!");
return;
}
resultCallback.onSuccess(body);
}
@Override
public void onFailure(Call<Categories> call, Throwable t) {
resultCallback.onError(t.getMessage());
}
});
}
//同步操作方式
public static Categories getGankCategoriesSync() throws IOException {
Call<Categories> gankCategories = getGankApi().getGankCategories();
return gankCategories.execute().body();
}
public interface ResultCallback<T> {
void onSuccess(T result);
void onError(String message);
}
}
d. 简单测试一下
textView = findViewById(R.id.textView);
//异步测试
NetworkUtil.getGankCategories(new ResultCallback<Categories>() {
@Override
public void onSuccess(Categories results) {
textView.setText(results.toString());
}
@Override
public void onError(String message) {
textView.setText(message);
}
});
//同步测试
//同步方式,比较麻烦,下面测试都是异步方法测试
Callable<Categories> categoriesCallable = new Callable<Categories>() {
@Override
public Categories call() throws Exception {
return NetworkUtil.getGankCategoriesSync();
}
};
try {
Categories categories = getThreadPool().submit(categoriesCallable).get();
textView.setText(categories.toString());
} catch (ExecutionException e) {
e.printStackTrace();
textView.setText(e.getMessage());
} catch (InterruptedException e) {
e.printStackTrace();
textView.setText(e.getMessage());
}
image.png
3. 动态的url访问@PATH
如 https://gank.io/api/data/Android/10/1
分类数据: http://gank.io/api/data/数据类型/请求个数/第几页
- 数据类型: 福利 | Android | iOS | 休息视频 | 拓展资源 | 前端 | all
- 请求个数: 数字,大于0
- 第几页:数字,大于0
实体类:Stories.java
package com.dxl.retrofittest.Model;
/**
* Copyright 2018 bejson.com
*/
import java.util.Date;
import java.util.List;
/**
* Auto-generated: 2018-09-23 8:7:44
*
* @author bejson.com (i@bejson.com)
* @website http://www.bejson.com/java2pojo/
*/
public class Stories {
private boolean error;
private List<Results> results;
@Override
public String toString() {
return "Stories{" +
"error=" + error +
", results=" + results +
'}';
}
public class Results {
private String _id;
private Date createdAt;
private String desc;
private Date publishedAt;
private String source;
private String type;
private String url;
private boolean used;
private String who;
@Override
public String toString() {
return "Results{" +
"_id='" + _id + '\'' +
", createdAt=" + createdAt +
", desc='" + desc + '\'' +
", publishedAt=" + publishedAt +
", source='" + source + '\'' +
", type='" + type + '\'' +
", url='" + url + '\'' +
", used=" + used +
", who='" + who + '\'' +
'}';
}
}
}
接口 GankApi.java
public interface GankApi {
...
//http://gank.io/api/data/Android/10/1
@GET("data/{type}/{count}/{page}")
Call<Stories> getGankStories(@Path("type") String type, @Path("count") int count, @Path("page") int page);
}
请求方法:
public static void getGankStories(String type, int page, int count, ResultCallback<Stories> resultCallback){
Call<Stories> gankStories = getGankApi().getGankStories(type, count, page);
gankStories.enqueue(new Callback<Stories>() {
@Override
public void onResponse(Call<Stories> call, Response<Stories> response) {
Stories body = response.body();
if (body == null) {
resultCallback.onError("body is null");
return;
}
resultCallback.onSuccess(body);
}
@Override
public void onFailure(Call<Stories> call, Throwable t) {
resultCallback.onError(t.getMessage());
}
});
}
4. @Query
@GET("News")
Call<NewsBean> getItem(@Query("newsId") String newsId, @Query("type") String type);
参数不确定:
@GET("News")
Call<NewsBean> getItem(@QueryMap Map<String, String> map);
参考:
https://blog.csdn.net/lmj623565791/article/details/51304204
https://www.jianshu.com/p/7687365aa946
https://blog.csdn.net/c__chao/article/details/78573737
https://gank.io/api