Android news api with retrofit and gson
Here's an example of how to use the Android News API with Retrofit and Gson:
Step 1: Add dependencies
Add the following dependencies to your build.gradle
file:
dependencies {
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
implementation 'com.google.code.gson:gson:2.8.6'
}
Step 2: Create the API interface
Create a new interface NewsApi
that defines the API endpoints:
public interface NewsApi {
@GET("v2/top-headlines")
Call<NewsResponse> getTopHeadlines(@Query("country") String country, @Query("category") String category);
@GET("v2/everything")
Call<NewsResponse> getEverything(@Query("q") String query, @Query("from") String from, @Query("to") String to);
}
Step 3: Create the NewsResponse model
Create a new class NewsResponse
that represents the response from the API:
public class NewsResponse {
private List<Article> articles;
public List<Article> getArticles() {
return articles;
}
}
public class Article {
private String title;
private String description;
private String url;
private String urlToImage;
public String getTitle() {
return title;
}
public String getDescription() {
return description;
}
public String getUrl() {
return url;
}
public String getUrlToImage() {
return urlToImage;
}
}
Step 4: Create the Retrofit instance
Create a new instance of Retrofit and specify the API interface and the base URL:
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://newsapi.org/")
.addConverterFactory(GsonConverterFactory.create())
.build();
NewsApi newsApi = retrofit.create(NewsApi.class);
Step 5: Make the API call
Use the NewsApi
instance to make the API call:
Call<NewsResponse> call = newsApi.getTopHeadlines("us", "technology");
call.enqueue(new Callback<NewsResponse>() {
@Override
public void onResponse(Call<NewsResponse> call, Response<NewsResponse> response) {
NewsResponse newsResponse = response.body();
List<Article> articles = newsResponse.getArticles();
// Process the articles
}
@Override
public void onFailure(Call<NewsResponse> call, Throwable t) {
// Handle the error
}
});
Step 6: Parse the response
Use Gson to parse the response:
Gson gson = new Gson();
NewsResponse newsResponse = gson.fromJson(response.body().toString(), NewsResponse.class);
That's it! You should now have a working example of using the Android News API with Retrofit and Gson.
Note: Make sure to replace the country
and category
parameters in the getTopHeadlines
method with the desired values. Also, make sure to handle errors and exceptions properly in your code.