1

Im trying to get the json data from below URL

https://newsapi.org/v2/everything?q=tesla&from=2021-05-07&sortBy=publishedAt&apiKey=c9e4ed47388d413c8af23fc46a330f8e

But when I run the app it shows

31029-31125 E/Volley: [228776] NetworkUtility.shouldRetryException: Unexpected response code 403 for https://newsapi.org/v2/everything?q=tesla&from=2021-02-23&sortBy=publishedAt&apiK 20ey=c9e4ed47388d413c8af23fc46a330f8e
31029-31125 E/Volley: [228776] NetworkUtility.shouldRetryException: Unexpected response code 403 for https://newsapi.org/v2/everything?q=tesla&from=2021-02-23&sortBy=publishedAt&apiK 20ey=c9e4ed47388d413c8af23fc46a330f8e

But when I enter the URL in chrome browser it shows the json data normally but I got getting the same thing in my app here is my code in kotlin

fun getNews(context: Context){
    var queue: RequestQueue = Volley.newRequestQueue(context)
    val url = "https://newsapi.org/v2/everything?q=tesla&from=2021-05-07&sortBy=publishedAt&apiKey=c9e4ed47388d413c8af23fc46a330f8e"
    val request = JsonObjectRequest(
        Request.Method.GET, url, null,
        { response ->
            var list: MutableList<newModel> = mutableListOf<newModel>()
            try {
                var rootArray: JSONArray = response.getJSONArray("articles")
                for(i in 0 until response.length()){
                    var dataObject: JSONObject = rootArray.get(i) as JSONObject
                    list.add(newModel(dataObject.getString("urlToImage") , dataObject.getString("title") , dataObject.getString("description") , dataObject.getString("url")))
                }

            } catch (e: Exception) {
                Toast.makeText(
                    context,
                    "error while parsing the jsonObject/array",
                    Toast.LENGTH_LONG
                ).show()
            }
            callBack.gotTheNewsData(list)
        }) { error ->
        Toast.makeText(context, "Error in responce", Toast.LENGTH_SHORT).show()
    }
    queue.add(request)
}
Tehleel Mir
  • 743
  • 8
  • 27

3 Answers3

2

I was facing the same error and I solved it by passing a header "Mozilla/5.0" to the request.

This can be done in this way on your code.

fun getNews(context: Context){
var queue: RequestQueue = Volley.newRequestQueue(context)
val url = "Your URL here"

val request = object: JsonObjectRequest(
    Request.Method.GET, url, null,
    { response ->
        var list: MutableList<newModel> = mutableListOf<newModel>()
        try {
            var rootArray: JSONArray = response.getJSONArray("articles")
            for(i in 0 until response.length()){
                var dataObject: JSONObject = rootArray.get(i) as JSONObject
                list.add(newModel(dataObject.getString("urlToImage") , dataObject.getString("title") , dataObject.getString("description") , dataObject.getString("url")))
            }

        } catch (e: Exception) {
            Toast.makeText(
                context,
                "error while parsing the jsonObject/array",
                Toast.LENGTH_LONG
            ).show()
        }
        callBack.gotTheNewsData(list)
    }) { error ->
    Toast.makeText(context, "Error in responce", Toast.LENGTH_SHORT).show()
}

// overriding function to add Headers.
{
    override fun getHeaders(): MutableMap<String, String> {
        val headers = HashMap<String, String>()
        headers["User-Agent"]="Mozilla/5.0"
        return headers
    }
}

queue.add(request)
}

It is important to use the object keyword before the construction of the request in order to be able to override the getHeaders() method.

This answer helped me in adding a custom header in Volley request with kotlin.

0
  1. Override header ["User-Agent"]="Mozilla/5.0"
  2. Or You can use this NewsApi which dont require apikey https://github.com/SauravKanchan/NewsAPI
0
@Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            HashMap<String, String> headers = new HashMap<>();
            headers.put("User-Agent", "Mozilla/5.0");

            return headers;
        }

Java version for ones who need it.

Darian Pudic
  • 45
  • 2
  • 10