【领券联盟】笔记:视频15-请求分类数据
破小布的小花狗
发表于
2020-03-27 05:45
1757
课堂笔记
课前准备
- 修改 LogUtils :把 Class clazz 改成 Object object
public class LogUtils {
private static int currentLev = 4;
private static final int DEBUG_LEV = 4;
private static final int INFO_LEV = 3;
private static final int WARNING_LEV = 2;
private static final int ERROR_LEV = 1;
public static void d(Object object,String log) {
if(currentLev >= DEBUG_LEV) {
Log.d(object.getClass().getSimpleName(),log);
}
}
public static void i(Object object,String log) {
if(currentLev >= INFO_LEV) {
Log.i(object.getClass().getSimpleName(),log);
}
}
public static void w(Object object,String log) {
if(currentLev >= WARNING_LEV) {
Log.w(object.getClass().getSimpleName(),log);
}
}
public static void e(Object object,String log) {
if(currentLev >= ERROR_LEV) {
Log.e(object.getClass().getSimpleName(),log);
}
}
}
- 添加网络访问权限
<uses-permission android:name="android.permission.INTERNET" />
课堂笔记
- 在 model 文件夹下创建接口 Api
public interface Api {
@GET("discovery/categories")
Call<Categories> getCategories();
}
- 在 utils 文件夹下创建单例类 RetrofitManager
public class RetrofitManager {
private static final RetrofitManager ourInstance = new RetrofitManager();
private final Retrofit mRetrofit;
public static RetrofitManager getInstance() {
return ourInstance;
}
private RetrofitManager() {
mRetrofit = new Retrofit.Builder()
.baseUrl(Constant.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
public Retrofit getRetrofit() {
return mRetrofit;
}
}
常量 BASE_URL 在 utils 文件夹下常量类 Constant 中创建
public class Constant {
public static final String BASE_URL = "https://api.sunofbeach.net/shop/api/";
}
- 获取 请求分类数据 的代码
@Override
public void getCategories() {
Retrofit retrofit = RetrofitManager.getInstance().getRetrofit();
Api api = retrofit.create(Api.class);
Call<Categories> task = api.getCategories();
task.enqueue(new Callback<Categories>() {
@Override
public void onResponse(Call<Categories> call, Response<Categories> response) {
int code = response.code();
LogUtils.d(HomePresenterImpl.this, "HomePresenterImpl code ----->" + code);
if (code == HttpURLConnection.HTTP_OK) {
//请求成功
Categories body = response.body();
LogUtils.d(HomePresenterImpl.this, "HomePresenterImpl body ----->" + body.toString());
} else {
//请求失败
LogUtils.i(HomePresenterImpl.this, "请求失败....");
}
}
@Override
public void onFailure(Call<Categories> call, Throwable t) {
//请求失败
LogUtils.i(HomePresenterImpl.this, "请求失败....");
}
});
}
学习感悟
- 这节课如果有同学程序一直崩,需要在 module gradle 中 android 下加以下代码
compileOptions{
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
- Android 初学者一名,请老师和各位同学讨论指正