Skip to content Skip to sidebar Skip to footer

Unexpected Response Code 403 (but Work Fine In Browser)

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

Solution 1:

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.

fungetNews(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 in0 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.
{
    overridefungetHeaders(): 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.

Solution 2:

  1. Override header ["User-Agent"]="Mozilla/5.0"
  2. Or You can use this NewsApi which dont require apikey https://github.com/SauravKanchan/NewsAPI

Post a Comment for "Unexpected Response Code 403 (but Work Fine In Browser)"