You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Volley调用API无法获取响应数据,返回403错误但API状态为200

解决Volley调用NewsAPI返回403错误的方案

常见原因及对应解决办法:

  • 添加自定义User-Agent请求头
    NewsAPI的反爬机制会拦截缺少浏览器标识的请求,Volley默认请求头不带User-Agent,这是导致403的高频原因。给StringRequest添加User-Agent:
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
        response -> {
            try {
                JSONObject jsonObject = new JSONObject(response);
                JSONArray jsonArray = jsonObject.getJSONArray("articles"); // 注意这里字段是articles而非results
                if(jsonArray.length()>0){
                    for(int i =0; i < 10; i++){
                        JSONObject jsonObject1 = jsonArray.getJSONObject(i);
                        String nTitle = jsonObject1.getString("title");
                        data.add(new ModelRV(nTitle));
                    }
                }
            }catch (Exception e){
                e.printStackTrace();
                Toast.makeText(MainActivity.this, "解析数据失败", Toast.LENGTH_SHORT).show();
            }
        },
        error -> {
            Log.e("Volley", "错误码: " + error.networkResponse.statusCode);
            Toast.makeText(MainActivity.this, "请求失败: " + error.getMessage(), Toast.LENGTH_SHORT).show();
        }) {
    @Override
    public Map<String, String> getHeaders() throws AuthFailureError {
        HashMap<String, String> headers = new HashMap<>();
        headers.put("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36");
        return headers;
    }
};
  • 检查API密钥有效性
  1. 登录NewsAPI后台查看请求次数:免费版每月限1000次请求,超限后会返回403。
  2. 确认密钥未被禁用,且未设置IP白名单限制(如果开启了白名单,要确保当前设备IP在列表内)。
  • 修正JSON解析字段
    你的代码里用results数组,但NewsAPItop-headlines接口返回的文章数组字段是articles,这个错误会导致解析异常,修正后才能正确处理返回数据。

  • 排查网络环境
    如果设备使用代理或VPN,可能被NewsAPI拦截,切换到常规网络重试。

内容的提问来源于stack exchange,提问作者kannan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 08:50:25