Retrofit簡單介紹
Retrofit是Square提供的開源產品,爲Android平臺的應用提供一個類型安全的REST客戶端。它是基於註解,提供 JSON to POJO(Plain Ordinary Java Object ,簡單 Java 對象),POJO to JSON,網絡請求(POST,GET, PUT,DELETE 等)封裝。
Retrofit 雖然是一套註解形的網絡請求封裝庫,但是它的強大在於讓代碼結構更給爲清晰,它可以直接解析JSON數據變成JAVA對象,甚至支持回調操作,處理不同的結果。
官方文檔地址:http://square.github.io/retrofit/
github地址:https://github.com/square/retrofit
基本使用
添加依賴
在AndroidStudio的項目中,在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'
數據格式的相關使用
今天我們使用聚合數據平臺的免費的一個笑話的接口,數據的返回格式是json,所以我們需要根據相應的json數據,建立自己的javabean。
在建立實體類之前,我們截圖,先讓大家看一下測試的接口。
API接口
通過接口我們可以看到以下信息:
主機地址:http://japi.juhe.cn
接口地址:/joke/content/list.from
數據格式爲json
根據json數據建立自己的javabean
JokeInfo.class實體類如下:
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":"女生分手的原因有兩個,\r\n一個是:閨蜜看不上。另一個是:閨蜜看上了。","hashId":"607ce18b4bed0d7b0012b66ed201fb08","unixtime":1418815439,"updatetime":"2014-12-17 19:23:59"},{"content":"老師講完課後,問道\r\n\u201c同學們,你們還有什麼問題要問嗎?\u201d\r\n這時,班上一男同學舉手,\r\n\u201c老師,這節什麼課?\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 : 女生分手的原因有兩個,
* 一個是:閨蜜看不上。另一個是:閨蜜看上了。
* 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;
}
}
}
}
定義服務接口
因爲是獲取笑話的一個接口,我給它命名爲: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的請求方式
@Query 是接口查詢的關鍵字
封裝接口服務的包裝類
這個接口服務的包裝類使用了單例模式,如下:
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";
}
}
如何調用
咱們先看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();
//這裏顯示了列表中的第一條的內容,所以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();
}
});
}
}
進一步解釋
-
首先調用我們封裝的網絡庫,創建retrofit和對應的接口服務jokeService。
-
然後調用我們的請求接口方法getJokeInfoList();
-
發送請求,並回調處理結果,call.enqueue();
API接口
通過接口我們可以看到以下信息:
主機地址:http://japi.juhe.cn
接口地址:/joke/content/list.from
數據格式爲json
根據json數據建立自己的javabean
JokeInfo.class實體類如下:
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":"女生分手的原因有兩個,\r\n一個是:閨蜜看不上。另一個是:閨蜜看上了。","hashId":"607ce18b4bed0d7b0012b66ed201fb08","unixtime":1418815439,"updatetime":"2014-12-17 19:23:59"},{"content":"老師講完課後,問道\r\n\u201c同學們,你們還有什麼問題要問嗎?\u201d\r\n這時,班上一男同學舉手,\r\n\u201c老師,這節什麼課?\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 : 女生分手的原因有兩個,
* 一個是:閨蜜看不上。另一個是:閨蜜看上了。
* 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;
}
}
}
}
定義服務接口
因爲是獲取笑話的一個接口,我給它命名爲: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的請求方式
@Query 是接口查詢的關鍵字
封裝接口服務的包裝類
這個接口服務的包裝類使用了單例模式,如下:
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";
}
}
如何調用
咱們先看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();
//這裏顯示了列表中的第一條的內容,所以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();
}
});
}
}
進一步解釋
-
首先調用我們封裝的網絡庫,創建retrofit和對應的接口服務jokeService。
-
然後調用我們的請求接口方法getJokeInfoList();
-
發送請求,並回調處理結果,call.enqueue();