java - API在android studio中不断返回401,但在浏览器中返回ok
问题描述
我目前正在尝试通过创建一个新闻应用程序并使用https://newsapi.org上的其余 API 来学习 MVVM 。我正在使用 retrofit2 调用 API,但我不断收到错误消息。我通过在我想接收响应的位置放置一个断点来调试应用程序,问题是当我尝试使用 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;
}
}
解决方案
您在这两种情况下提供的 http 标头可能存在问题。
尝试通过嗅探http协议数据进行调试,并比较两者。看看你错过了什么...
推荐阅读
- excel - 库存问题,只有在有库存时才收货
- laravel - Laravel Nova:将字段动态绑定到模型上的 JSON 属性
- java - 迭代器中的无限循环
- postgresql - postgres 索引表现不清楚
- python - 使用列表理解找到最小数字
- post - 邮递员 - 将用户发布到 BIM 360 错误?
- java - Spring Thymeleaf classappend 不附加类
- mysql - 禁用 Doctrine 自动查询
- css - Vuejs在css中应用循环来放置悬停
- android - Android - RecyclerView StaggeredGridLayoutManager 拉伸最后一行的宽度