Can anyone help me understand why I am unable to get data from internet?
I am trying to get data from newsapi.org insde my News app using retrofit library. I don't know what's the problem. Please help.
NewsApiService.kt

package com.example.newsapp.network

import com.example.newsapp.model.News
import com.squareup.moshi.Moshi
import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory
import retrofit2.Retrofit
import retrofit2.converter.moshi.MoshiConverterFactory
import retrofit2.http.GET
import retrofit2.http.Headers
import retrofit2.http.Query

private const val BASE_URL = "https://newsapi.org/"

private val moshi = Moshi.Builder()
    .add(KotlinJsonAdapterFactory())
    .build()

private val retrofit = Retrofit.Builder()
    .addConverterFactory(MoshiConverterFactory.create(moshi))
    .baseUrl(BASE_URL)
    .build()

interface NewsApiService {
    @Headers("country: in", "apiKey: 4fd028e0cf3a410180f97029e7237ae7")
    @GET("v2/top-headlines")
    suspend fun getNewsHeadLines(): News

    @Headers("country: in", "apiKey: 4fd028e0cf3a410180f97029e7237ae7")
    @GET("v2/top-headlines")
    suspend fun getNewsByCategory(@Query("category") category: String): News
}

object NewsApi {
    val retrofitService: NewsApiService by lazy { retrofit.create(NewsApiService::class.java) }
}

News.kt

package com.example.newsapp.model

import com.fasterxml.jackson.annotation.JsonIgnoreProperties

@JsonIgnoreProperties(ignoreUnknown = true)
data class News(
    val status: String,
    val articles: List<Article>
)

@JsonIgnoreProperties(ignoreUnknown = true)
data class Article(
    val title: String,
    val description: String,
    val url: String,
    val urlToImage: String,
    val content: String?
)

NewsViewModel.kt

package com.example.newsapp

import android.util.Log
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.newsapp.network.NewsApi
import kotlinx.coroutines.launch

class NewsViewModel : ViewModel() {
    init {
        viewModelScope.launch {
            Log.d("adfasdf", "Here")
            try {
                val news = NewsApi.retrofitService.getNewsHeadLines()
            } catch (e: Exception) {
                Log.d("adfalkj", e.toString())
            }
        }
    }
}

This is the image of parsed JSON response
enter image description here

I am using this api
https://newsapi.org/docs/endpoints/top-headlines

This is the error (Log.d inside the NewsViewModel)

---------------------------- PROCESS STARTED (6024) for package com.example.newsapp ----------------------------
2023-06-19 21:34:55.993  6024-6024  adfalkj                 com.example.newsapp                  D  retrofit2.HttpException: HTTP 401 

谢谢你的帮助

推荐答案

根据the documentation的说法,API密钥需要通过三种方式之一提供:

  • 作为apiKey查询参数
  • 作为X-API-Key个HTTP标头
  • 使用Authentication HTTP标头

这些都不是你做的.您使用的是标头,但标头名称为apiKey.

您可以try :

interface NewsApiService {
    @Headers("country: in", "X-API-Key: 4fd028e0cf3a410180f97029e7237ae7")
    @GET("v2/top-headlines")
    suspend fun getNewsHeadLines(): News

    @Headers("country: in", "X-API-Key: 4fd028e0cf3a410180f97029e7237ae7")
    @GET("v2/top-headlines")
    suspend fun getNewsByCategory(@Query("category") category: String): News
}

这会将HTTP头更改为X-API-Key,以符合文档的要求.

Android相关问答推荐

垂直居中图标

房间打开创建回调java.nio.channels. OverlappingFilLockResponse

Jetpack编写Lazy列滑动删除动画不顺利结束

如何清除导航抽屉中以前 Select 的项目(Jetpack Compose)

如何将Unicode符号作为文本居中放置在布局中的按钮(Android XML)中?

在Android 14/SDK 34中使用RegisterReceiver的正确方式是什么?

由于Xcode运行脚本阶段没有指定输出,在IOS Emulator中的KMM项目中生成失败

Play store 的 Play 完整性与 Firebase 应用判断 Play 完整性

在 kotlin 协同 routine 中,如何将数据范围限定为请求路径(以 MDC 为例)?

为什么 Android Studio 中的 theme.xml 目录没有任何原色

具有数据库和升级潜力的移动应用程序开发(Android)供朋友使用

Compose 状态不是 recomposing

我该怎么做文本计时器

是否可以在 Kotlin 中为 mutableStateOf() 设置自定义设置器

Compose Accompaniist Pager 中的 TabRow/Tab 重组问题

如何放置在柱子的角落(底端)

Jetpack Compose:SpanStyle 的 TextAlign(垂直居中)

如何在包含 Jetpack Compose 内容的布局中使用权重

在 Compose 中使用 DeepLink 会导致无法向后导航

为什么我不能在屏幕外拿任何物体