本博客仅做学习笔记,如有侵权,联系后即刻更改
科普:
//网络数据申请
implementation("com.squareup.okhttp3:okhttp:4.9.3")
implementation'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
//RetrofitUtils
implementation 'com.squareup.okhttp3:logging-interceptor:4.9.3'
annotationProcessor 'androidx.room:room-compiler:2.3.0'
import android.util.Log;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class RetrofitUtils {
public static Retrofit getRetrofit(String url) {
//日志显示级别
HttpLoggingInterceptor.Level level= HttpLoggingInterceptor.Level.BODY;
//新建log拦截器
HttpLoggingInterceptor loggingInterceptor=new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
@Override
public void log(String message) {
Log.d("RetrofitMessage","OkHttp====Message:"+message);
}
});
loggingInterceptor.setLevel(level);
//定制OkHttp
OkHttpClient.Builder httpClientBuilder = new OkHttpClient
.Builder();
//OkHttp进行添加拦截器loggingInterceptor
httpClientBuilder.addInterceptor(loggingInterceptor);
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(url)
.addConverterFactory(GsonConverterFactory.create())
.client( httpClientBuilder.build())
.build();
return retrofit;
}
}
import com.hnucm.coursedesign.Type.TypeHistory;
import com.hnucm.coursedesign.Type.TypeMusic;
import com.hnucm.coursedesign.Type.TypeNews;
import com.hnucm.coursedesign.Type.TypePoetry;
import com.hnucm.coursedesign.Type.TypeSearchNews;
import com.hnucm.coursedesign.Type.TypeVideos;
import com.hnucm.coursedesign.Type.TypeWeatherResponse;
import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Header;
import retrofit2.http.Query;
public interface Api {
// https://api.asilu.com/today
@GET("today")
Call<TypeHistory> getHistory();
}
import java.util.List;
public class TypeHistory {
public int code;
public String month;
public String day;
public List<DataDTO> data;
public static class DataDTO {
public int year;
public String title;
public String link;
public String type;
}
}
// 加载历史上的今天的API资源
Api api = RetrofitUtils.getRetrofit("https://api.asilu.com").create(Api.class);
Call<TypeHistory> historyCall = api.getHistory();
historyCall.enqueue(new Callback<TypeHistory>() {
@Override
public void onResponse(Call<TypeHistory> call, Response<TypeHistory> response) {
TypeHistory typeHistory = response.body();
myAdapter2 = new MyAdapter();
recyclerView.setAdapter(myAdapter2);
num = typeHistory.data.size();
for (int i=0; i < num; i++){
year_list.add(typeHistory.data.get(i).year);
title_list.add(typeHistory.data.get(i).title);
historyUrl_list.add(typeHistory.data.get(i).link);
}
myAdapter2.notifyDataSetChanged();
}
@Override
public void onFailure(Call<TypeHistory> call, Throwable t) {
}
});
}
小小励志
有些事你现在不做,一辈子都不会做了。
如果你想做一件事,全世界都会为你让路。
《搭车去柏林》