android 意外的响应代码403(但在浏览器中工作正常)

vbopmzt1  于 2023-03-27  发布在  Android
关注(0)|答案(3)|浏览(299)

我试图从下面的URL获取JSON数据
https://newsapi.org/v2/everything?q=tesla&from=2021-05-07&sortBy=publishedAt&apiKey=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
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

但是当我在Chrome浏览器中输入URL时,它通常会显示JSON数据,但我在我的应用程序中得到了同样的东西,这里是我在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)
}
eaf3rand

eaf3rand1#

我也遇到了同样的错误,我通过向请求传递一个标题 “Mozilla/5.0” 来解决它。
这可以在你的代码中以这种方式完成。

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)
}

为了能够覆盖getHeaders()方法,在构造请求之前使用object关键字非常重要。
This answer帮助我使用Kotlin在Volley请求中添加了一个自定义头。

au9on6nz

au9on6nz2#

  1. Override header [“User-Agent”]=“Mozilla/5.0”
    1.或者你可以使用这个不需要apikey https://github.com/SauravKanchan/NewsAPI的NewsApi
aiqt4smr

aiqt4smr3#

@Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            HashMap<String, String> headers = new HashMap<>();
            headers.put("User-Agent", "Mozilla/5.0");

            return headers;
        }

Java版本为那些谁需要它。

相关问题