我在GitHub上遇到了一个惊人的免费新闻应用程序,但我不知道如何在改造中实现它
这个API是NEWSAPI的破解版本,具有相同的功能,我只想知道如何在改造中实现代码。
API文档
BASE_URL = "https://saurav.tech/NewsAPI/“
"/top-headlines/category//.json“= top_headlines_api
everything_api =“/URL/..json”
在上面的文档中,我对如何在改造客户端传递.json感到困惑,请帮助!
发布于 2020-10-28 09:28:36
好的,所以我想出了如何在改造2中实现上面的内容。
在您的改装请求接口中使用下面的代码(在我的例子中是它的GetNewsByCountry.java )
public interface GetNewsByCountry {
@GET("top-headlines/category/general/{country}.json")
Call<NEWSPOJO> getAllNews(@Path("country") String country);
}
现在,在您的改装客户端实例中,编写以下代码
public class RetrofitClientInstance {
public static final String BASE_URL = "https://saurav.tech/NewsAPI/";
private static Retrofit retrofit = null;
public static Retrofit getRetrofitInstance() {
if (retrofit==null) {
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
}
注意:我为上面的代码创建了不同的类,即GetNewsByCountry、java和RetrofitClientInstance.java。
最后,要进行HTTP调用,请在活动/片段类中编写以下代码
GetNewsByCountry service = RetrofitClientInstance.getRetrofitInstance()
.create(GetNewsByCountry.class);
Call<YOUR_POJO_CLASS> call = service.getAllNews("us");
call.enqueue(new Callback<YOUR_POJO_CLASS>() {
@Override
public void onResponse(Call<YOUR_POJO_CLASS> call, Response<YOUR_POJO_CLASS> response) {
/** TODO: implement the logic you want when you receive the
JSON data, most probably you want to show
the result in recycler view so I am pasting
my code here, u know just in case
Log.v("onResponse", "we are in th on response callback");
assert response.body() != null;
List<Article> list = response.body().getArticles();
adapter = new NewsAdapter(getActivity(), list);
recyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
*/
}
@Override
public void onFailure(Call<NEWSPOJO> call, Throwable t) {
/** progressDialog.dismiss();
Log.e("“out”", t.toString());
Toast.makeText(getActivity(), "Something went wrong...Please try later!", Toast.LENGTH_SHORT).show();
*/
}
});
如果你还有任何疑问,请发表评论!
https://stackoverflow.com/questions/64474923
复制相似问题