Retrofit调用NewsAPI遭遇HTTP 401错误,求技术支援
解决Retrofit调用NewsAPI出现HTTP 401未授权错误
HTTP 401错误表示请求未通过服务端权限验证,针对你的代码和场景,按以下步骤排查解决:
1. 修正API Key的传递格式
NewsAPI官方要求API Key的传递格式不符合你当前的写法,服务端无法识别权限信息,需调整为以下两种正确方式之一:
方式1:使用Authorization请求头
修改NewsApiService.kt中的@Headers注解,改用Bearer Token格式:
interface NewsApiService { @Headers( "Authorization: Bearer 4fd028e0cf3a410180f97029e7237ae7", "country: in" ) @GET("v2/top-headlines") suspend fun getNewsHeadLines(): News @Headers( "Authorization: Bearer 4fd028e0cf3a410180f97029e7237ae7", "country: in" ) @GET("v2/top-headlines") suspend fun getNewsByCategory(@Query("category") category: String): News }
方式2:将API Key作为查询参数传递(更推荐)
直接在请求中通过@Query传递apiKey,完全匹配官方文档示例:
interface NewsApiService { @GET("v2/top-headlines") suspend fun getNewsHeadLines( @Query("country") country: String = "in", @Query("apiKey") apiKey: String = "4fd028e0cf3a410180f97029e7237ae7" ): News @GET("v2/top-headlines") suspend fun getNewsByCategory( @Query("country") country: String = "in", @Query("category") category: String, @Query("apiKey") apiKey: String = "4fd028e0cf3a410180f97029e7237ae7" ): News }
2. 验证API Key的有效性
- 登录NewsAPI后台,确认你的API Key无拼写错误、状态为启用
- 免费版API Key仅允许
localhost请求,若用真机/非localhost模拟器测试,需升级付费版或在后台添加允许的请求来源 - 检查API Key是否超出每日调用限额,超限后也会返回401
3. 额外优化:统一JSON解析库
你的数据类使用Jackson的@JsonIgnoreProperties,但Retrofit配置的是Moshi转换器,可能导致后续JSON解析失败,建议替换为Moshi注解:
import com.squareup.moshi.JsonClass @JsonClass(generateAdapter = true) data class News( val status: String, val articles: List<Article> ) @JsonClass(generateAdapter = true) data class Article( val title: String, val description: String, val url: String, val urlToImage: String, val content: String? )
4. 确认网络权限
确保AndroidManifest.xml中添加了网络访问权限:
<uses-permission android:name="android.permission.INTERNET" />
内容的提问来源于stack exchange,提问作者Abinash Dash
相关产品推荐
相关产品推荐

