skip to Main Content

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 

Thanks for helping

2

Answers


  1. According to the documentation, the API key needs to be supplied in one of three ways:

    • As an apiKey query parameter
    • As an X-API-Key HTTP header
    • Using the Authentication HTTP header

    You are doing none of these. You are using the header, but with apiKey as the header name.

    You could 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
    }
    

    This changes the HTTP header to X-API-Key to match what the documentation calls for.

    Login or Signup to reply.
  2. just pass the Header with api key like method param

    @GET("...")
    fun yourMethod(
      @Header key: String = YOUR_API_KEY
    ): Response
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search