MainActivity.java
RetrofitInstance.getInstance().api.getPosts("everything").enqueue(new Callback<Post>() {
@Override
public void onResponse(@NonNull Call<Post> call, @NonNull Response<Post> response) {
Post posts = response.body();
Toast.makeText(context, Objects.requireNonNull(posts).getArticles().get(0).getTitle(), Toast.LENGTH_SHORT).show();
}
@Override
public void onFailure(@NonNull Call<Post> call, @NonNull Throwable t) {
}
});
API.java
public interface Api {
@Headers("apiKey: <Secret Key>")
@GET("v2/{newsType}/")
Call<Post> getPosts(@Path("newsType") String newsType);
}
RetroInterface.java
public class RetrofitInstance {
public static RetrofitInstance instance;
Api api;
RetrofitInstance() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://newsapi.org/")
.addConverterFactory(GsonConverterFactory.create())
.build();
api = retrofit.create(Api.class);
}
public static RetrofitInstance getInstance() {
if (instance == null) {
instance = new RetrofitInstance();
}
return instance;
}
}
Post.java
public class Post {
private ArrayList<Articles> articles;
public ArrayList<Articles> getArticles() {
return articles;
}
}
Articles.java
public class Articles {
private String urlToImage, title, details, author;
public String getUrlToImage() {
return urlToImage;
}
public String getTitle() {
return title;
}
public String getDetails() {
return details;
}
public String getAuthor() {
return author;
}
}
错误: com.newsapi.app.EverythingFragment$1.onResponse(EverythingFragment.java:53) 在retrofit2.DefaultCallAdapterFactory$ExecutorCallbackCall$1.lambda$onResponse$0$retrofit2-DefaultCallAdapterFactory$ExecutorCallbackCall$1(DefaultCallAdapterFactory.java:89)
我们必须使用查询字符串参数来传递 apiKey,而不是通过标头传递。看看下面的例子:
API.java
public interface Api {
@GET("v2/{newsType}?q=a&apiKey=<Secret-Key>")
Call<Post> getPosts(@Path("newsType") String newsType);
}
你必须输入你的 API 密钥,代码才能完美运行。