Flutter Web使用Dio请求Google News RSS返回403错误求助
Flutter Web请求Google News RSS返回403错误及CORS问题解决
解决403错误核心方案:模拟浏览器请求头
Google News的反爬机制会识别非浏览器环境的请求,Dio默认请求头与浏览器差异较大,导致触发403限制。需完全模拟主流浏览器的请求头:
final response = await _dio.get( 'https://news.google.com/rss/search?q=ev%20charger&hl=en-GB&gl=GB&ceid=GB:en', options: Options( headers: { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8', 'Accept-Language': 'en-GB,en;q=0.5', 'Referer': 'https://news.google.com/', }, ), ); return RssFeed.parse(response.data);
- 关键要点:
User-Agent需使用当前主流浏览器的真实标识,可通过浏览器开发者工具复制请求头获取;Referer设置为Google News主页,模拟站内跳转的请求行为;- 若仍返回403,可复制浏览器请求中所有非敏感的
Request Headers(如Accept-Encoding等)添加到Dio请求头中。
解决CORS跨域问题
Flutter Web运行在浏览器环境下受同源策略限制,即使解决403,仍可能触发CORS错误,需通过代理服务器中转请求:
1. 搭建简单代理服务器(以Node.js为例)
const express = require('express'); const axios = require('axios'); const app = express(); app.get('/rss-proxy', async (req, res) => { try { const rssUrl = 'https://news.google.com/rss/search?q=ev%20charger&hl=en-GB&gl=GB&ceid=GB:en'; const response = await axios.get(rssUrl, { headers: { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8', 'Accept-Language': 'en-GB,en;q=0.5', 'Referer': 'https://news.google.com/', } }); res.set('Content-Type', 'application/rss+xml'); res.send(response.data); } catch (err) { res.status(err.response?.status || 500).send(err.message); } }); app.listen(3000, () => console.log('Proxy server running on http://localhost:3000'));
2. Flutter Web请求代理地址
final response = await _dio.get('http://localhost:3000/rss-proxy'); return RssFeed.parse(response.data);
- 部署注意:线上环境需将代理服务器与Flutter Web部署在同一域名下,或在代理服务器配置CORS规则允许前端域名访问。
额外注意事项
- Google反爬机制会动态调整,若后续再次出现403,需更新请求头为最新的浏览器标识;
- 避免高频请求,建议添加请求间隔或本地缓存机制,降低被限制的风险。
内容的提问来源于stack exchange,提问作者khan
相关产品推荐
相关产品推荐

