I am currently trying to learn MVVM by creating a news app and using the rest API at https://newsapi.org. I am calling the API using retrofit2, but I keep getting a error. I debugged the app by placing a breakpoint at the position where I am suppose to receive the response and the problem is that when I try to make a call to the API in android studio using the API key I always get a 401 error, but when I make the same call in a browser I am successful. Why is this?
Here is my code.
API Interface
import java.util.ArrayList;
import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Query;
public interface ApiInterface {
@GET("top-headlines")
Call<ArrayList<NewsArticles>> getNewsList(@Query("country")String country, @Query("apiKey") String
apiKey);
}
The Repository where I make the call.
public class Repository {
public Repository() {
}
static final String BASE_URL = "https://newsapi.org/v2/";
MutableLiveData<ArrayList<NewsArticles>> newsArticleList = new MutableLiveData<>();
Gson gson = new GsonBuilder()
.setLenient()
.create();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
ApiInterface apiInterface = retrofit.create(ApiInterface.class);
Call<ArrayList<NewsArticles>> call = apiInterface.getNewsList("us","api");
public MutableLiveData<ArrayList<NewsArticles>> getCall() {
call.enqueue(new Callback<ArrayList<NewsArticles>>() {
@Override
public void onResponse(Call<ArrayList<NewsArticles>> call, Response<ArrayList<NewsArticles>> response) {
if (response.isSuccessful()) {
newsArticleList.setValue(response.body());
}
}
@Override
public void onFailure(Call<ArrayList<NewsArticles>> call, Throwable t) {
t.printStackTrace();
}
});
return newsArticleList;
}
}