我目前正在尝试通过创建一个新闻应用程序并使用https://newsapi.org上的rest API来学习MVVM。我正在使用retrofit2调用接口,但我一直收到错误。我通过在我应该接收响应的位置放置一个断点来调试应用程序,问题是当我尝试使用API密钥调用android studio中的API时,我总是得到401错误,但当我在浏览器中进行相同的调用时,我成功了。为什么会这样呢?
这是我的代码。
API接口
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);
}我进行调用的存储库。
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;
}
}发布于 2021-05-26 03:41:14
在API接口中显式指定您的头应该是有效的。
public interface ApiInterface {
@Headers(
value = [
"Accept: application/json",
"Content-type:application/json"]
)
}发布于 2021-05-26 02:51:07
也许在这两种情况下您提供的http头文件都有问题。
尝试通过嗅探http协议数据进行调试,并将两者进行比较。看看你错过了什么。
https://stackoverflow.com/questions/67693584
复制相似问题