谷歌浏览器和火狐浏览器对HTML的嗅探(Sniff)能力

如下样例代码, 返回网站首页HTML内容

java 复制代码
import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Controller;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.util.Objects;


@Controller
@RequestMapping
public class FrontController {

    @ResponseBody
    @GetMapping("/")
    public void store(HttpServletRequest request) {
        String homePage = "http://t.infuq.com/data/static/sniff.html";
        /** http://t.infuq.com/data/static/sniff.html 内容如下
<!--
2025.10.22
-->
<!DOCTYPE html>
<html lang>
    <head>
        <meta charset="utf-8">
        <title>MyTitle</title>
    </head>
    <body>
        <p>https://www.infuq.com http://t.infuq.com</p>
    </body>
</html>
        */
        read(homePage);
    }

    private void read(String url) {
        InputStream in = ResourceUtils.getURL(url).openStream();
        HttpServletResponse response = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getResponse();
        IOUtils.copy(in, response.getOutputStream());
    }
}

当通过 Chrome 或 Microsoft Edge 访问时可以正常显示内容如下

但是通过火狐浏览器访问时, 却显示了源码

查看响应头信息

服务端没有返回Content-Type, 火狐浏览器(64位 v144.0)通过嗅探能力, 判断该文件是text/plain文件, 而 Chrome 等浏览器会把该文件识别成text/html文件.

【解决】

1.在服务端指定响应Content-Type

response.setContentType("text/html");

2.将HTML源码顶部的注释去掉

html 复制代码
把
<!--
2025.10.22
-->
<!DOCTYPE html>
<html lang>
    <head>
        <meta charset="utf-8">
        <title>MyTitle</title>
    </head>
    <body>
        <p>https://www.infuq.com http://t.infuq.com</p>
    </body>
</html>

改成 
<!DOCTYPE html>
<html lang>
    <head>
        <meta charset="utf-8">
        <title>MyTitle</title>
    </head>
    <body>
        <p>https://www.infuq.com http://t.infuq.com</p>
    </body>
</html>

https://source.chromium.org/chromium/chromium/src/+/refs/tags/118.0.5981.4:net/base/mime_sniffer.cc

相关推荐
will_net1 分钟前
Vue IIS部署 api 访问当前站点 代理跳转真实API 问题
前端·javascript·vue.js
weixin_449173654 分钟前
react 的useEffect用法
前端·javascript·react.js
涛涛ing13 分钟前
2026年的前端:你引以为傲的框架,正在被浏览器原生能力“架空”
前端
计算机魔术师15 分钟前
23项AI技术要管了:大模型API还出口得了吗?
前端
凤城老人17 分钟前
ZhyCMS成长日记:一个企业 CMS 从 1.0 到 3.1.3 的折腾史
前端
小羊没烦恼!38 分钟前
T-SQL查询高级—SQL Server索引中的碎片和填充因子
开发语言·前端·javascript·数据库·后端·python·web安全
定栓1 小时前
Webpack迁到Vite第一节:模块系统迁移:require → import
运维·前端·webpack
小熊在忙fpga1 小时前
N32G430芯片的flash表示
前端·javascript·html
Data analyse4561 小时前
App埋点版本兼容的字段迁移校验
大数据·运维·服务器·前端·数据库·数据分析
todoitbo1 小时前
本来只想给内网开个口子,Natapp 却多给了一道防护
前端·javascript·vue.js·内网穿透·网络防护·natapp