转载自:http://blog.csdn.net/jdsjlzx/article/details/52015347
什么是 Retrofit ?
Retrofit 是一套 RESTful 架构的 Android(Java) 客户端实现,基于注解,提供 JSON to POJO(Plain Ordinary Java Object ,简单 Java 对象),POJO to JSON,网络请求(POST,GET, PUT,DELETE 等)封装。
配置环境
在build.gradle中添加
.....
compile 'io.reactivex:rxjava:1.1.6'
compile 'io.reactivex:rxandroid:1.2.1'
compile 'com.squareup.okhttp3:okhttp:3.3.1'
compile 'com.squareup.retrofit2:retrofit:2.1.0'
compile 'com.squareup.retrofit2:converter-gson:2.1.0'
compile 'com.squareup.retrofit2:adapter-rxjava:2.1.0'
compile 'com.squareup.okhttp3:logging-interceptor:3.3.1'
说明:
Retrofit默认依赖于okhttp,所以需要集成okhttp。
API返回的数据为JSON格式,在此我使用的是Gson对返回数据解析.请使用最新版的Gson 。
接口
这里我们调试借助百度名人名言API
该接口的API主机地址为:http://apistore.baidu.com;
需要访问的接口:avatardata/mingrenmingyan/lookup;
需要一个key等于apikey的Header和一个keyword等于名人名言的查询关键字,而且该请求为GET请求.
接口返回json格式:
{
"total": 10,
"result": [
{
"famous_name": "佚名",
"famous_saying": "婚姻是一家私人专门银行,存储真爱和默契,提取幸福和快乐。夫妻双方互为账户,且存折是活期的,可以随存随取,而家庭则是这家银行里的柜台,通过它,夫妻双方可以把自己的喜怒哀乐尽情地存进对方的银行里,并可随时提取微笑、鼓励、安慰、体贴、温柔等利息。"
},
{
"famous_name": "英国",
"famous_saying": "真爱无坦途"
},
{
"famous_name": "狄太人",
"famous_saying": "一个人真爱的时候,甚至会想不到自己是爱着对方。"
},
{
"famous_name": "佚名",
"famous_saying": "所有的阻碍,全是对真爱的淬炼。"
},
{
"famous_name": "罗兰",
"famous_saying": "当你真爱一个人的时候,你是会忘记自己的苦乐得失,而只是关心对方的苦乐得失的。"
},
{
"famous_name": "罗兰",
"famous_saying": "当两人之间有真爱情的时候,是不会考虑到年龄的问题,经济的条件,相貌的美丑,个子的高矮,等等外在的无关紧要的因素的。假如你们之间存在着这种问题,那你要先问问自己,是否真正在爱才好。"
},
{
"famous_name": "佚名",
"famous_saying": "真正的勇气是来自内心的真爱。"
},
{
"famous_name": "佚名",
"famous_saying": "天国般的幸福,存在于对真爱的希望。"
},
{
"famous_name": "狄太人",
"famous_saying": "一个人真爱的时候,甚至会想不到自己是爱着对方"
},
{
"famous_name": "Shakespeare",
"famous_saying": "通向真爱的路从无坦途。"
}
],
"error_code": 0,
"reason": "Succes"
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
定义实体类
我们根据上面API返回的json数据来创建一个Famous数据对象,我们可以利用AndroidStudio插件 GsonFormat 快速方便的将json数据转为Java 对象。
Famous.java
public class Famous {
public int total;
public int error_code;
public String reason;
public List<FamousInfo> result;
public static class FamousInfo {
public String famous_name;
public String famous_saying;
}
}
注意:如果你的字段有跟json不一样的,要在字段上面加注解@SerializedName,@SerializedName是指定Json格式中的Key名。
如上面的错误码字段,你就像定义为code,而服务器返回的是error_code,这个时候就应该这么写:
@SerializedName("error_code")
public int code;
使用
首先定义
public abstract class BaseApi {
public static final String API_SERVER = "服务器地址"
private static final OkHttpClient mOkHttpClient = new OkHttpClient();
private static Retrofit mRetrofit;
protected static Retrofit getRetrofit() {
if (Retrofit == null) {
Context context = Application.getInstance().getApplicationContext();
mOkHttpClient.setConnectTimeout(30, TimeUnit.SECONDS);
mOkHttpClient.networkInterceptors()
.add(new CookiesInterceptor(context));
File cacheDirectory = new File(context.getCacheDir()
.getAbsolutePath(), "HttpCache");
Cache cache = new Cache(cacheDirectory, 20 * 1024 * 1024);
mOkHttpClient.setCache(cache);
mRetrofit = new Retrofit.Builder()
.baseUrl(API_SERVER + "/")
.setDateFormat("yyyy-MM-dd HH:mm:ss")
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.client(mOkHttpClient)
.build();
}
return mRetrofit;
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
定义FamousApi
public class FamousApi extends BaseApi{
private interface FamousService {
@GET("/avatardata/mingrenmingyan/lookup")
Observable<Famous> getFamousList(@Header("apiKey") String apiKey,
@Query("keyword") String keyword,
@Query("page") int page,
@Query("rows") int rows);
}
protected static final FamousService service = getRetrofit().create(FamousService.class);
public static Observable<UserProfileResp> getFamousList(String apiKey,String keyword, int page, int rows){
return service.getFamousList(apiKey, keyword, page, rows);
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
最终使用:
public void getFamousList(){
FamousApi.getFamousList("apiKey","人才",1,20)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Subscriber<Famous>(){
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
}
@Override
public void onNext(Famous famous) {
List<FamousInfo> list = famous.result;
}
});
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
如下效果:
参考demo:https://github.com/jdsjlzx/RetrofitDemo