這一篇文章就正式開始講解Retrofit的使用:
1卿城、先去官網(wǎng)找到依賴:
官網(wǎng)地址:https://github.com/square/retrofit
添加依賴:
implementation "com.squareup.retrofit2:retrofit:2.9.0"
溫馨提示:在這里因?yàn)槲掖蛩阋脭r截器贬循,然后發(fā)現(xiàn)是要添加依賴:
implementation("com.squareup.okhttp3:logging-interceptor:4.8.1")
但是后來想了下焊切,雖然Retrofit是已經(jīng)封裝了Okhttp赐劣,但是我用的版本號(hào)可以對(duì)得上么?
于是就找了下竖幔,果然對(duì)不上暮的,這里先說下怎么核對(duì)哈:
(提示下:我目前還是在用windows10系統(tǒng)的,但是大致方法應(yīng)該是一樣的)
①感挥、打開項(xiàng)目的
②目胡、找到
③、打開本地的文件
④链快、打開這個(gè)文件
⑤誉己、搜索下okhttp,然后就找到下面的版本號(hào)啦域蜗!
老衲欣慰露出了微笑巨双,又get了一個(gè)小技巧。
2霉祸、添加轉(zhuǎn)換方法筑累,因?yàn)榉?wù)器返回的都是json字符串,但是retrofit的轉(zhuǎn)換方法需要你去告訴它丝蹭,怎么轉(zhuǎn)化慢宗,所以需要添加轉(zhuǎn)換的方法,點(diǎn)開官網(wǎng)的retrofit-converters然后找到你需要的轉(zhuǎn)化的類型,添加對(duì)應(yīng)的依賴就可以了
這里就特別說明下:在我們添加官網(wǎng)轉(zhuǎn)換類型的依賴時(shí):
implementation 'com.squareup.retrofit2:converter-gson:latest.version'
會(huì)出現(xiàn)報(bào)錯(cuò)镜沽,說找不到對(duì)應(yīng)的api配置敏晤。這個(gè)時(shí)候就需要更換下:
implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
把latest.version替換成最新版本號(hào),也就是跟retrofit2的版本號(hào)保持一直就好了
使用方法如下:
1缅茉、創(chuàng)建RetrofitImpl嘴脾,對(duì)于配置需求的話,都在這里進(jìn)行配置蔬墩,因?yàn)镽etrofit是封裝了Okhttp的译打,所以對(duì)于OkHttpClient也是需要Okhttpde 知識(shí)的
public class RetrofitImpl {
private static RetrofitImpl sInstance=new RetrofitImpl();
public static RetrofitImpl getsInstance(){
return sInstance;
}
private Retrofit mRetrofit;
public static Retrofit getmRetrofit(){
return sInstance.mRetrofit;
}
private RetrofitImpl(){
HttpLoggingInterceptor logging = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
@Override
public void log(String message) {
Log.d("jeffrey",message);
}
});
logging.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(logging)
.build();
mRetrofit=new Retrofit.Builder()
.client(client)
//添加轉(zhuǎn)化的類型
.addConverterFactory(GsonConverterFactory.create())
.baseUrl("")
.build();
}
}
2、創(chuàng)建接口拇颅,請(qǐng)求類型以及參數(shù)需要在這里進(jìn)行聲明奏司,然后說下上面的baseUrl是接口地址前一截相同的部分,然后在@GET("")填寫對(duì)應(yīng)的后半截
public interface IApi {
@GET("")
Call<Result> get(@Header ("anthor") String author,@Query("username") String username);
@POST("")
@FormUrlEncoded
Call<Result> post(@Field("username")String username);
@POST("")
@Multipart
Call<Result> postMultipart(@Part("username")RequestBody username);
@POST("")
Call<Result> postJson(@Body RequestBody jsonBody);
}
3樟插、創(chuàng)建實(shí)體類韵洋,這個(gè)是依據(jù)接口文檔返回的參數(shù)進(jìn)行配置
public class Result {
public int errorCode;
public String errorMsg;
public Data data;
public static class Data{
public String ip;
public String params;
public HashMap<String,String> headers;
public String json;
}
}
4、在java后臺(tái)這里編寫邏輯
public class Retrofit extends AppCompatActivity {
private Button mBtnGet,mBtnPost,mBtnPostMultipart,mBtnPostJson;
private TextView mTvContent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_retrofit);
initViews();
initEvents();
}
private void initEvents() {
mBtnGet.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
IApi api= RetrofitImpl.getmRetrofit().create(IApi.class);
api.get("jeffrey","123").enqueue(new Callback<Result>() {
@Override
public void onResponse(Call<Result> call, Response<Result> response) {
Result result=response.body();
mTvContent.setText(result.errorCode+","+result.errorMsg+","+result.data);
}
@Override
public void onFailure(Call<Result> call, Throwable t) {
Toast.makeText(Retrofit.this,"網(wǎng)絡(luò)發(fā)生錯(cuò)誤",Toast.LENGTH_SHORT).show();
}
});
}
});
mBtnPost.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
IApi api= RetrofitImpl.getmRetrofit().create(IApi.class);
api.post("jeffrey").enqueue(new Callback<Result>() {
@Override
public void onResponse(Call<Result> call, Response<Result> response) {
Result result=response.body();
mTvContent.setText(result.errorCode+","+result.errorMsg+","+result.data);
}
@Override
public void onFailure(Call<Result> call, Throwable t) {
Toast.makeText(Retrofit.this,"網(wǎng)絡(luò)發(fā)生錯(cuò)誤",Toast.LENGTH_SHORT).show();
}
});
}
});
mBtnPostMultipart.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
IApi api= RetrofitImpl.getmRetrofit().create(IApi.class);
MediaType mediaType=MediaType.get("text/plain;charset=utf-8");
RequestBody username=RequestBody.create(mediaType,"jeffrey");
api.postMultipart(username).enqueue(new Callback<Result>() {
@Override
public void onResponse(Call<Result> call, Response<Result> response) {
Result result=response.body();
mTvContent.setText(result.errorCode+","+result.errorMsg+","+result.data);
}
@Override
public void onFailure(Call<Result> call, Throwable t) {
Toast.makeText(Retrofit.this,"網(wǎng)絡(luò)發(fā)生錯(cuò)誤",Toast.LENGTH_SHORT).show();
}
});
}
});
mBtnPostJson.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
IApi api= RetrofitImpl.getmRetrofit().create(IApi.class);
MediaType mediaType=MediaType.get("application/json;charset=utf-8");
RequestBody username=RequestBody.create(mediaType,"{\"name\":\"jeffrey\",\"age\":18}");
api.postJson(username).enqueue(new Callback<Result>() {
@Override
public void onResponse(Call<Result> call, Response<Result> response) {
Result result=response.body();
mTvContent.setText(result.errorCode+","+result.errorMsg+","+result.data.json);
}
@Override
public void onFailure(Call<Result> call, Throwable t) {
Toast.makeText(Retrofit.this,"網(wǎng)絡(luò)發(fā)生錯(cuò)誤",Toast.LENGTH_SHORT).show();
}
});
}
});
}
private void initViews() {
mBtnGet=findViewById(R.id.bt_get);
mTvContent=findViewById(R.id.tv_content);
mBtnPost=findViewById(R.id.bt_post);
mBtnPostMultipart=findViewById(R.id.bt_post_multipart);
mBtnPostJson=findViewById(R.id.bt_post_json);
}
}
這里小結(jié)一下:對(duì)比使用okhttp來說岸夯,retrofit使用起來方便了不少,在配置好Retrofit的構(gòu)造之后们妥,只需要在聲明中的添加對(duì)應(yīng)的聲明猜扮,就可以直接使用,emmmm的確是個(gè)神兵利器监婶,然后下一章會(huì)寫關(guān)于EventBus的介紹旅赢,感謝各位的支持!