作為一名Android開發(fā)者,如果你沒有聽說過Retrofit網(wǎng)絡請求框架,那真的是太不應該了。好吧,這篇文章的目的就是普及基本知識了。
首先,Retrofit是由Square開發(fā)出來的一套網(wǎng)絡請求底層框架,可以理解為OKHttp的加強版(PS:OKHttp也是他家的)。本質上網(wǎng)絡請求的工作是由OkHttp完成,而 Retrofit 僅負責網(wǎng)絡請求接口的封裝。它的一個最大的特點是通過大量的設計模式對代碼進行解耦,同時支持同步、異步和RxJava,以及可以配置不同的反序列化工具來解析數(shù)據(jù),如json、xml等
簡單介紹完Retrofit之后,想必你還是一頭霧水對吧,下面通過一個簡單的小例子來講解一下。
首先,你要進行網(wǎng)絡請求,必須要有對應的服務器對吧,但是呢,要移動端開發(fā)人員去搭建一個后臺環(huán)境也太麻煩了,于是乎可以利用SpringBoot快速搭建一個本地服務器來進行數(shù)據(jù)交互.
- IntelliJ IDEA直接創(chuàng)建一個Spring Assistant項目(這個應該不用教了吧~實在不會可以google一下)
public class Response<T> {
private int code;
private int count;
private String msg;
private T data;
public Response(int code, int count, String msg, T data) {
this.code = code;
this.count = count;
this.msg = msg;
this.data = data;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
}
@RestController
public class HelloController {
@RequestMapping("getAuthCode")
public Response getAuthCode(String phone, int type) {
return new Response(0,0,"succes",phone+",i know you want authcode!");
}
}
直接運行SpringXXXApplication,后臺就成功運行了
- Android Studio新建項目
1.配置Gradle,添加依賴
// Okhttp
implementation 'com.squareup.okhttp3:okhttp:3.7.0'
// Retrofit
implementation 'com.squareup.retrofit2:retrofit:2.1.0'
別忘了要在AndroidManifest申請網(wǎng)絡權限喲
<uses-permission android:name="android.permission.INTERNET"/>
2.新建一個接口ApiService.java,通過注解的方式配置網(wǎng)絡請求參數(shù)
public interface ApiService {
@GET("getAuthCode")
Call<ResponseBody> getAuthCode(@Query("phone") String phone, @Query("type") int type);
}
3.在MainActivity里面進行網(wǎng)絡請求
private void requestRetrofit() {
Retrofit retrofit = new Retrofit.Builder().baseUrl("http://192.168.20.227:8080/").build();
ApiService apiService = retrofit.create(ApiService.class);
Call<ResponseBody> call = apiService.getAuthCode("183****2568",0);
call.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, retrofit2.Response<ResponseBody> response) {
try {
Log.e("MainActivity",response.body().string().toString());
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
t.printStackTrace();
}
});
}
okay,這樣就可以直接運行項目了,你會看到如下log
E/MainActivity: {"code":0,"count":0,"msg":"succes","data":"183****2568,okay,i know you want authcode!"}
這樣就完成了最基本的Retrofit網(wǎng)絡請求了。