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

HttpUrlConnection请求URL返回404,但浏览器可正常访问的问题求助

解决HttpURLConnection请求返回404但浏览器可访问的问题

可能的原因及修复方案

1. 错误添加AJAX专属请求头

你的代码中设置了X-Requested-With: XMLHttpRequest请求头,这个头用于标识AJAX异步请求,但浏览器直接访问目标URL时,发送的是普通GET请求,不会携带该头。部分服务器会根据这个头区分请求类型,拒绝AJAX请求访问普通页面路径,从而返回404。

修复:
移除connection.setRequestProperty("X-Requested-With", "XMLHttpRequest");这一行代码。

2. 未处理HTTP重定向

很多网站会自动将HTTP请求重定向到HTTPS或调整路径,浏览器会自动跟随重定向,但HttpURLConnection默认可能未开启重定向跟随(部分版本默认关闭)。

修复:
添加重定向跟随设置:

connection.setInstanceFollowRedirects(true);

或者直接将URL替换为HTTPS版本:https://meteo.bg/bg/osnOpasni

3. 补充缺失的必要请求头

除User-Agent外,部分网站会校验Accept-Language等请求头,缺失可能导致服务器返回异常。可以补充常见请求头:

connection.setRequestProperty("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8");

修改后的完整代码示例

URL meteo = new URL("https://meteo.bg/bg/osnOpasni");
HttpURLConnection connection = (HttpURLConnection) meteo.openConnection();
connection.setRequestMethod("GET");
connection.setInstanceFollowRedirects(true);
connection.setRequestProperty("Connection", "keep-alive");
connection.setRequestProperty("Accept", "text/html, */*");
connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36");
connection.setRequestProperty("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8");

int responseCode = connection.getResponseCode();
// 后续读取HTML内容的逻辑

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 18:03:27