1. Gradle配置
implementation 'com.squareup.retrofit2:retrofit:2.4.0'
implementation 'com.squareup.retrofit2:converter-gson:2.4.0'
2. 基本的get請(qǐng)求
我們使用GankApi 來(lái)進(jìn)行測(cè)試。
如: 獲取閑讀的主分類 https://gank.io/api/xiandu/categories
獲取結(jié)果如下:
{
"error":false,
"results":[
{
"_id":"57c83777421aa97cbd81c74d",
"en_name":"wow",
"name":"科技資訊",
"rank":1
},
{
"_id":"57c83577421aa97cb162d8b1",
"en_name":"apps",
"name":"趣味軟件/游戲",
"rank":5
},
.....
]
}
a. 編寫實(shí)體類 Categorise.java
這個(gè)可以用一些工具自動(dòng)生成實(shí)體類。不需要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. 定義一個(gè)接口對(duì)象GankApi.java
public interface GankApi {
//完整url: https://gank.io/api/xiandu/categories 姥宝,https://gank.io/api/作為baseUrl
@Get("xiandu/categories")
Call<Categories> getCategories();
}
c. 創(chuàng)建retrofit并進(jìn)行數(shù)據(jù)請(qǐng)求
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. 簡(jiǎn)單測(cè)試一下
textView = findViewById(R.id.textView);
//異步測(cè)試
NetworkUtil.getGankCategories(new ResultCallback<Categories>() {
@Override
public void onSuccess(Categories results) {
textView.setText(results.toString());
}
@Override
public void onError(String message) {
textView.setText(message);
}
});
//同步測(cè)試
//同步方式,比較麻煩,下面測(cè)試都是異步方法測(cè)試
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());
}
3. 動(dòng)態(tài)的url訪問(wèn)@PATH
如 https://gank.io/api/data/Android/10/1
分類數(shù)據(jù): http://gank.io/api/data/數(shù)據(jù)類型/請(qǐng)求個(gè)數(shù)/第幾頁(yè)
- 數(shù)據(jù)類型: 福利 | Android | iOS | 休息視頻 | 拓展資源 | 前端 | all
- 請(qǐng)求個(gè)數(shù): 數(shù)字驶俊,大于0
- 第幾頁(yè):數(shù)字剥汤,大于0
實(shí)體類: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);
}
請(qǐng)求方法:
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);
參數(shù)不確定:
@GET("News")
Call<NewsBean> getItem(@QueryMap Map<String, String> map);
參考:
https://blog.csdn.net/lmj623565791/article/details/51304204
http://www.reibang.com/p/7687365aa946
https://blog.csdn.net/c__chao/article/details/78573737
https://gank.io/api