Retrofit簡(jiǎn)單介紹
Retrofit是Square提供的開源產(chǎn)品,為Android平臺(tái)的應(yīng)用提供一個(gè)類型安全的REST客戶端。它是基于注解,提供 JSON to POJO(Plain Ordinary Java Object ,簡(jiǎn)單 Java 對(duì)象)自晰,POJO to JSON滩褥,網(wǎng)絡(luò)請(qǐng)求(POST犁跪,GET杨帽, PUT,DELETE 等)封裝悠反。
Retrofit 雖然是一套注解形的網(wǎng)絡(luò)請(qǐng)求封裝庫(kù)残黑,但是它的強(qiáng)大在于讓代碼結(jié)構(gòu)更給為清晰馍佑,它可以直接解析JSON數(shù)據(jù)變成JAVA對(duì)象,甚至支持回調(diào)操作萍摊,處理不同的結(jié)果挤茄。
官方文檔地址:http://square.github.io/retrofit/
github地址:https://github.com/square/retrofit
基本使用
添加依賴
在AndroidStudio的項(xiàng)目中如叼,在build.gradle文件中添加以下引用:
compile 'com.squareup.retrofit2:retrofit:2.0.1'
compile 'com.squareup.retrofit2:converter-gson:2.0.0-beta3'
compile 'com.google.code.gson:gson:2.3'
數(shù)據(jù)格式的相關(guān)使用
今天我們使用聚合數(shù)據(jù)平臺(tái)的免費(fèi)的一個(gè)笑話的接口冰木,數(shù)據(jù)的返回格式是json,所以我們需要根據(jù)相應(yīng)的json數(shù)據(jù)笼恰,建立自己的javabean踊沸。
在建立實(shí)體類之前,我們截圖社证,先讓大家看一下測(cè)試的接口逼龟。
API接口
通過(guò)接口我們可以看到以下信息:
主機(jī)地址:http://japi.juhe.cn
接口地址:/joke/content/list.from
數(shù)據(jù)格式為json
根據(jù)json數(shù)據(jù)建立自己的javabean
JokeInfo.class實(shí)體類如下:
package com.loonggg.retrofitdemo;
import java.util.List;
/**
* Created by loongggdroid on 2016/4/14.
*/
public class JokeInfo {
/**
* error_code : 0
* reason : Success
* result : {"data":[{"content":"女生分手的原因有兩個(gè),\r\n一個(gè)是:閨蜜看不上追葡。另一個(gè)是:閨蜜看上了腺律。","hashId":"607ce18b4bed0d7b0012b66ed201fb08","unixtime":1418815439,"updatetime":"2014-12-17 19:23:59"},{"content":"老師講完課后,問(wèn)道\r\n\u201c同學(xué)們宜肉,你們還有什么問(wèn)題要問(wèn)嗎匀钧?\u201d\r\n這時(shí),班上一男同學(xué)舉手谬返,\r\n\u201c老師之斯,這節(jié)什么課?\u201d","hashId":"20670bc096a2448b5d78c66746c930b6","unixtime":1418814837,"updatetime":"2014-12-17 19:13:57"}]}
*/
private int error_code;
private String reason;
private ResultBean result;
public int getError_code() {
return error_code;
}
public void setError_code(int error_code) {
this.error_code = error_code;
}
public String getReason() {
return reason;
}
public void setReason(String reason) {
this.reason = reason;
}
public ResultBean getResult() {
return result;
}
public void setResult(ResultBean result) {
this.result = result;
}
public static class ResultBean {
/**
* content : 女生分手的原因有兩個(gè)遣铝,
* 一個(gè)是:閨蜜看不上佑刷。另一個(gè)是:閨蜜看上了。
* hashId : 607ce18b4bed0d7b0012b66ed201fb08
* unixtime : 1418815439
* updatetime : 2014-12-17 19:23:59
*/
private List<DataBean> data;
public List<DataBean> getData() {
return data;
}
public void setData(List<DataBean> data) {
this.data = data;
}
public static class DataBean {
private String content;
private String hashId;
private int unixtime;
private String updatetime;
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getHashId() {
return hashId;
}
public void setHashId(String hashId) {
this.hashId = hashId;
}
public int getUnixtime() {
return unixtime;
}
public void setUnixtime(int unixtime) {
this.unixtime = unixtime;
}
public String getUpdatetime() {
return updatetime;
}
public void setUpdatetime(String updatetime) {
this.updatetime = updatetime;
}
}
}
}
定義服務(wù)接口
因?yàn)槭谦@取笑話的一個(gè)接口酿炸,我給它命名為:JokeService
package com.loonggg.retrofitdemo;
import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Query;
/**
* Created by loongggdroid on 2016/4/14.
*/
public interface JokeService {
@GET("/joke/content/list.from")
Call<JokeInfo> getJokeInfoList(@Query("sort") String sort, @Query("page") int page, @Query("pagesize") int pagesize, @Query("time") String time, @Query("key") String key);
}
注解:
@GET 是get的請(qǐng)求方式
@Query 是接口查詢的關(guān)鍵字
封裝接口服務(wù)的包裝類
這個(gè)接口服務(wù)的包裝類使用了單例模式瘫絮,如下:
package com.loonggg.retrofitdemo;
import android.content.Context;
import retrofit2.GsonConverterFactory;
import retrofit2.Retrofit;
/**
* Created by loongggdroid on 2016/4/13.
*/
public class RetrofitWrapper {
private static RetrofitWrapper instance;
private Context mContext;
private Retrofit retrofit;
private RetrofitWrapper() {
retrofit = new Retrofit.Builder().baseUrl(Constant.BASE_URL).addConverterFactory(GsonConverterFactory.create()).build();
}
public static RetrofitWrapper getInstance() {
if (instance == null) {
synchronized (RetrofitWrapper.class) {
instance = new RetrofitWrapper();
}
}
return instance;
}
public <T> T create(Class<T> service) {
return retrofit.create(service);
}
public class Constant {
public static final String BASE_URL = "http://api2.juheapi.com";
}
}
如何調(diào)用
咱們先看MainActivity中的代碼,如下:
package com.loonggg.retrofitdemo;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
JokeService jokeService = RetrofitWrapper.getInstance().create(JokeService.class);
Call<JokeInfo> call = jokeService.getJokeInfoList("desc", 1, 2, "1418816972", "eb46c85bea73462583e38b84c3a25c4b");
call.enqueue(new Callback<JokeInfo>() {
@Override
public void onResponse(Call<JokeInfo> call, Response<JokeInfo> response) {
JokeInfo ji = response.body();
//這里顯示了列表中的第一條的內(nèi)容填硕,所以get(0)
Toast.makeText(MainActivity.this, ji.getResult().getData().get(0).getContent(), Toast.LENGTH_LONG).show();
}
@Override
public void onFailure(Call<JokeInfo> call, Throwable t) {
Toast.makeText(MainActivity.this, t.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
}
進(jìn)一步解釋
- 首先調(diào)用我們封裝的網(wǎng)絡(luò)庫(kù)麦萤,創(chuàng)建retrofit和對(duì)應(yīng)的接口服務(wù)jokeService。
- 然后調(diào)用我們的請(qǐng)求接口方法getJokeInfoList();
- 發(fā)送請(qǐng)求廷支,并回調(diào)處理結(jié)果频鉴,call.enqueue();
到這里基本結(jié)束了,是不是非常簡(jiǎn)單恋拍?趕緊試試去吧垛孔。