首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >API在android studio中一直返回401,但在浏览器中返回ok

API在android studio中一直返回401,但在浏览器中返回ok
EN

Stack Overflow用户
提问于 2021-05-26 02:20:40
回答 2查看 48关注 0票数 0

我目前正在尝试通过创建一个新闻应用程序并使用https://newsapi.org上的rest API来学习MVVM。我正在使用retrofit2调用接口,但我一直收到错误。我通过在我应该接收响应的位置放置一个断点来调试应用程序,问题是当我尝试使用API密钥调用android studio中的API时,我总是得到401错误,但当我在浏览器中进行相同的调用时,我成功了。为什么会这样呢?

这是我的代码。

API接口

代码语言:javascript
复制
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);
}

我进行调用的存储库。

代码语言:javascript
复制
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;
}


}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2021-05-26 03:41:14

在API接口中显式指定您的头应该是有效的。

代码语言:javascript
复制
public interface ApiInterface {
   @Headers(
        value = [
            "Accept: application/json",
            "Content-type:application/json"]
    )
}
票数 0
EN

Stack Overflow用户

发布于 2021-05-26 02:51:07

也许在这两种情况下您提供的http头文件都有问题。

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67693584

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档