Retrofit 簡(jiǎn)介
Retrofit 是一套由Square所開發(fā)維護(hù)疲眷,將RESTfulAPI 寫法規(guī)范和模塊化的函數(shù)庫虎忌。底層也使用他們的Okhttp瓤球,Retrofit 2默認(rèn)使用OKHttp作為網(wǎng)絡(luò)層,并且在它上面進(jìn)行構(gòu)建微渠。
官方描述:用于Android和Java的一個(gè)類型安全(type-safe)的REST客戶端
你將會(huì)用注解去描述HTTP請(qǐng)求霎苗,同時(shí)Retrofit默認(rèn)集成URL參數(shù)替換和查詢參數(shù).除此之外它還支持 Multipart請(qǐng)求和文件上傳争剿。
添加依賴
compile'com.squareup.retrofit2:converter-gson:2.2.0'
compile'com.squareup.okhttp3:logging-interceptor:3.8.0'
定義接口
在這一步已艰,需要將我們的 API 接口地址轉(zhuǎn)化成一個(gè) Java 接口。
我們的 API 接口地址為:
轉(zhuǎn)化寫成 Java 接口為
public interface APIInterface{
@GET("/users/{user}")
Call<TestModel> repo(@Path("user") String user);
}
在此處 GET 的意思是 發(fā)送一個(gè) GET請(qǐng)求蚕苇,請(qǐng)求的地址為:baseUrl + "/users/{user}"哩掺。
{user} 類似于占位符的作用,具體類型由 repo(@Path("user") String user) 指定涩笤,這里表示 {user} 將是一段字符串嚼吞。
Call<TestModel> 是一個(gè)請(qǐng)求對(duì)象,<TestModel>表示返回結(jié)果是一個(gè) TestModel 類型的實(shí)例蹬碧。
定義 Model
請(qǐng)求會(huì)將 Json 數(shù)據(jù)轉(zhuǎn)化為 Java 實(shí)體類舱禽,所以我們需要自定義一個(gè) Model:
public class TestModel {
private String login;
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
}
進(jìn)行連接通信
現(xiàn)在我們有了『要連接的 Http 接口』和 『要返回的數(shù)據(jù)結(jié)構(gòu)』,就可以開始執(zhí)行請(qǐng)求啦恩沽。
首先誊稚,構(gòu)造一個(gè) Retrofit 對(duì)象:
Retrofit retrofit= new Retrofit.Builder()
.baseUrl("https://api.github.com")
.addConverterFactory(GsonConverterFactory.create())
.build();
注意這里添加的 baseUrl 和 GsonConverter,前者表示要訪問的網(wǎng)站罗心,后者是添加了一個(gè)轉(zhuǎn)換器里伯。
接著,創(chuàng)建我們的 API 接口對(duì)象渤闷,這里 APIInterface 是我們創(chuàng)建的接口:
APIInterface service = retrofit.create(APIInterface.class);
使用 APIInterface 創(chuàng)建一個(gè)『請(qǐng)求對(duì)象』:
Call<TestModel> model = service.repo("Guolei1130");
注意這里的 .repo("Guolei1130") 取代了前面的 {user}疾瓮。到這里,我們要訪問的地址就成了:
可以看出這樣的方式有利于我們使用不同參數(shù)訪問同一個(gè) Web API 接口飒箭,比如你可以隨便改成 .repo("ligoudan")
最后狼电,就可以發(fā)送請(qǐng)求了!
model.enqueue(new Callback<TestModel>() {
@Override
public void onResponse(Call<TestModel> call,
Response<TestModel>response) {
// Log.e("Test", response.body().getLogin());
System.out.print(response.body().getLogin());
}
@Override
public void onFailure(Call<TestModel> call, Throwable t) {
System.out.print(t.getMessage()); }
});
至此弦蹂,我們就利用 Retrofit 完成了一次網(wǎng)絡(luò)請(qǐng)求漫萄。
GET 請(qǐng)求參數(shù)設(shè)置
在我們發(fā)送 GET 請(qǐng)求時(shí),如果需要設(shè)置 GET 時(shí)的參數(shù)盈匾,Retrofit 注解提供兩種方式來進(jìn)行配置腾务。分別是 @Query(一個(gè)鍵值對(duì))和 @QueryMap(多對(duì)鍵值對(duì))。
Call<TestModel> one(@Query("username") String username);
Call<TestModel> many(@QueryMap Map<String, String> params);
POST 請(qǐng)求參數(shù)設(shè)置
POST 的請(qǐng)求與 GET 請(qǐng)求不同削饵,POST 請(qǐng)求的參數(shù)是放在請(qǐng)求體內(nèi)的岩瘦。
所以當(dāng)我們要為 POST 請(qǐng)求配置一個(gè)參數(shù)時(shí)未巫,需要用到 @Body 注解:
Call<TestModel> post(@Body User user);
這里的 User 類型是需要我們?nèi)プ远x的:
public class User {
public String username;
public String password;
public User(String username,String password){
this.username = username;
this.password = password;
}
最后在獲取請(qǐng)求對(duì)象時(shí):
User user = new User("lgd","123456");
Call<TestModel> model = service.post(user);
就能完成 POST 請(qǐng)求參數(shù)的發(fā)送,注意該請(qǐng)求參數(shù) user 也會(huì)轉(zhuǎn)化成 Json 格式的對(duì)象發(fā)送到服務(wù)器启昧。
以上內(nèi)容摘自: http://www.reibang.com/p/b64a2de066c3 (對(duì)作者表示感謝)
我的總結(jié)
// 在鏈接時(shí)會(huì)替換掉URL中{}中的內(nèi)容叙凡,例如:[http://your.api-base.url/group/123/users](http://your.api-base.url/group/123/users)
@GET("/group/{id}/users") //注意 字符串id
List<User> groupList(@Path("id") int groupId); //注意 Path注解的參數(shù)要和前面的字符串一樣 id
// 例如:(http://your.api-base.url/group/123/users)
@GET("/group/{id}/{name}")
List<User> groupList(@Path("id") int groupId, @Path("name") String name);
// 還支持查詢參數(shù),@Query相當(dāng)于在URL后加上問號(hào)和后面的參數(shù)密末,例如:(http://your.api-base.url/group/123/users?sort=1)
@GET("/group/{id}/users")
List<User> groupList(@Path("id") int groupId, @Query("sort") String sort);
// 多個(gè)Query之間通過&連接握爷,例如 (http://your.api-base.url/group/123/users?newsId=123&sort=1)
@GET("/group/{id}/users")
List<User> groupList(@Path("id") int groupId, @Query("newsId") String newsId, @Query("sort") String sort);
// 假如需要添加相同Key值,但是value卻有多個(gè)的情況严里,一種方式是添加多個(gè)@Query參數(shù)新啼,還有一種簡(jiǎn)便的方式是將所有的value放置在列表中,然后在同一個(gè)@Query下完成添加
// 例如:[http://your.api-base.url/group/123/users?newsId=123&newsId=345]
@GET("/group/{id}/users")
List<User> groupList(@Path("id") int groupId, @Query
("newsId") List<String> newsId);
// 也可以多個(gè)參數(shù)在URL問號(hào)之后刹碾,且個(gè)數(shù)不確定燥撞,例如(http://your.api-base.url/group/123/users?newsId=123&sort=1)
@GET("/group/{id}/users")
List<User> groupList(@Path("id") int groupId, @QueryMap
Map<String, String> map);
// 也可以為固定參數(shù)與動(dòng)態(tài)參數(shù)的混用
@GET("/group/{id}/users")
List<User> groupList(@Path("id") int groupId, @Query
("newsId") String newsId, @QueryMap Map<String, String> map);
// Query非必填,也就是說即使不傳該參數(shù)迷帜,服務(wù)端也可以正常解析物舒,但請(qǐng)求方法定義處還是需要完整的Query注解,某次請(qǐng)求如果不需要傳該參數(shù)的話戏锹,只需填充null即可
List<User> repos = service.groupList(123, null);
// 若需要重新定義接口地址冠胯,可以使用@Url,將地址以參數(shù)的形式傳入即可
@GET
Call<List<Activity>> getActivityList(@Url String url, @QueryMap Map<String, String> map);
對(duì)請(qǐng)求進(jìn)行統(tǒng)一封裝
public abstract class BaseRequest<M> {
protected abstract Call<M> getCall();
private int tag;
private WeakReference<IRequestCallback> callbackWeakReference;
public void exe(final IRequestCallback requestCallback, final int tag) {
final IRequestCallback callback = checkCallback();
if (callback == null) return;
callback.onRequestStart(tag);
getCall().enqueue(new Callback<M>() {
@Override
public void onResponse(Call<M> call, Response<M> response) {
if (response.isSuccessful()) {
if (callback == null) return;
callback.onRequestSucc(tag, response.body());
} else {
String error = response.message();
int code = response.code();
String message = code + ":" + error;
ServerException exception = new ServerException(message);
callback.onRequestException(tag, exception);
LogUtil.log("base response 錯(cuò)誤:" + message);
}
}
@Override
public void onFailure(Call<M> call, Throwable e) {
Throwable exception = e.getCause();
IRequestCallback callback = checkCallback();
if (callback == null) return;
callback.onRequestException(tag, (Exception) exception);
}
});
if (callback == null) return;
callback.onRequestFinal(tag);
}
public void cancel() {
getCall().cancel();
}
編寫service
public interface TestService {
@GET("jxc/merchant_info/query_merchant_info")
Call<UserInfoGson> getUserInfoJSON(@Query("merchantNo") String merchantNo);
/**
*
* 如果不需要轉(zhuǎn)換成Json數(shù)據(jù),可以用了ResponseBody;
* @param merchantNo
* @return
*/
@GET("jxc/merchant_info/query_merchant_info")
Call<ResponseBody> getUserInfoString(@Query("merchantNo") String merchantNo);
@GET("jxc/merchant_info/query_merchant_info")
Call<UserInfoGson> getUserInfoJSON(@QueryMap HashMap<String ,String> map);
/**
*
* POST JSON 請(qǐng)求, 結(jié)果不轉(zhuǎn)成GSON 使用String
*
* @param route
* @return
*/
@Headers({"Content-type:application/json;charset=UTF-8"})
@POST("/jxc/customer/add")
Call<ResponseBody> addMember(@Body RequestBody route);
@FormUrlEncoded
@POST("/jxc/customer/add")
Call<ResponseBody> addMember2(@Field("loginName") String username,
@Field("password") String password);
}
編寫request
public class UserInfoRequest extends BaseRequest<TestService> {
private HashMap<String , String> param;
public UserInfoRequest(HashMap<String, String> param) {
this.param = param;
}
//.getUserInfoJSON("66283")
@Override
protected Call<UserInfoGson> getCall() {
return NetFactory.getRetrofit().
create(getServiceClass()).
getUserInfoJSON(param);
}
@Override
protected Class<TestService> getServiceClass() {
return TestService.class;
}
}
發(fā)起請(qǐng)求
new UserInfoRequest(param).exe(callback, tag)
public class CustomConverterFactory extends Converter.Factory{
private Gson gson;
public CustomConverterFactory(Gson gson) {
this.gson = gson;
}
@Override
public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) {
//return super.responseBodyConverter(type, annotations, retrofit);
TypeAdapter<?> adapter = gson.getAdapter(TypeToken.get(type));
return new CustomResponseConverter<>(gson, adapter);
}
@Override
public Converter<?, RequestBody> requestBodyConverter(Type type, Annotation[] parameterAnnotations, Annotation[] methodAnnotations, Retrofit retrofit) {
return super.requestBodyConverter(type, parameterAnnotations, methodAnnotations, retrofit);
}
}
/**
- Created by hexiaoning on 2017/4/27.
- 參考:http://www.reibang.com/p/2263242fa02d
*/
public class CustomResponseConverter <T> implements Converter<ResponseBody, T> {
private final Gson gson;
private final TypeAdapter<T> adapter;
public CustomResponseConverter(Gson gson, TypeAdapter<T> adapter) {
this.gson = gson;
this.adapter = adapter;
}
@Override
public T convert(ResponseBody value) throws IOException {
try {
String body = value.string();
LogUtil.log("converter response: " + body);
return adapter.fromJson(body)
} catch (Exception e) {
throw new RuntimeException(e.getMessage());
} finally {
value.close();
}
}
}