Retrofit使用基础教程
基础依赖:implementation ‘com.squareup.retrofit2:retrofit:2.8.1’
如果想要用Retrofit获取Json字符串并自动转为Java实例对象,则还需要添加依赖:implementation ‘com.squareup.retrofit2:converter-gson:2.0.2’
以获取Json字符串为例:
1、创建API接口:
public interface API {
//使用注解来标明请求类型,并传入主网址下的分级网址(尖括号里则为返回实例的类型,默认为ResponseBody)
//纯获取Json字符串
@GET("/get/text")
Call<ResponseBody> getJsonStr();
//获取Json字符串,并解析为Java实例(需标明返回实例的泛型)
@GET("/get/text")
Call<JsonResult> getJsonResult();
}
2、只获取Json字符串
纯获取Json字符串,不解析
//创建Retrofit对象,设置baseUrl
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(MainActivity.BASE_URL)
.build();
//利用Retrofit对象创建自定义接口对象(API)
API api = retrofit.create(API.class);
Call call = api.getJsonStr();
call.enqueue(new Callback() {
@Override
public void onResponse(Call call, Response response) {
int responseCode = response.code();
Log.d(TAG, "responseCode ----> " + responseCode);
if (responseCode == HttpURLConnection.HTTP_OK) {
String JsonStr = response.body().string;
}
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable throwable) {
Log.d(TAG, "onFailure ----> " + throwable.toString());
}
});
获取Json字符串,并自动解析为Java实例
//创建Retrofit对象,设置baseUrl
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(MainActivity.BASE_URL)
//如果要自动解析Json字符串,必须要调用addConverterFactory()函数来添加解析器
.addConverterFactory(GsonConverterFactory.create())
.build();
//利用Retrofit对象创建自定义接口对象(API)
API api = retrofit.create(API.class);
Call call = api.getJsonResult();
call.enqueue(new Callback() {
@Override
public void onResponse(Call call, Response response) {
int responseCode = response.code();
Log.d(TAG, "responseCode ----> " + responseCode);
if (responseCode == HttpURLConnection.HTTP_OK) {
JsonResult jsonResult = response.body();
updateUI(jsonResult);
}
}
@Override
public void onFailure(Call<JsonResult> call, Throwable throwable) {
Log.d(TAG, "onFailure ----> " + throwable.toString());
}
});