首页 > 解决方案 > 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;
}


}

标签: javaandroidapimvvm

解决方案


您在这两种情况下提供的 http 标头可能存在问题。

尝试通过嗅探http协议数据进行调试,并比较两者。看看你错过了什么...


推荐阅读