谷歌浏览器和火狐浏览器对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

相关推荐
小李子呢021121 分钟前
前端八股Vue(6)---v-if和v-for
前端·javascript·vue.js
程序员buddha24 分钟前
ES6 迭代器与生成器
前端·javascript·es6
周周记笔记36 分钟前
初识HTML和CSS(一)
前端·css·html
aq553560037 分钟前
网页开发四剑客:HTML/CSS/JS/PHP全解析
javascript·css·html
chxii1 小时前
在 IIS 中实现 SSL 证书的自动续期
前端
周星星日记1 小时前
vue3中静态提升和patchflag实现
前端·vue.js·面试
橘子编程1 小时前
React 19 全栈开发实战指南
前端·react.js·前端框架
DanCheOo1 小时前
AI Streaming 架构:从浏览器到服务端的全链路流式设计
前端·agent
我是小趴菜2 小时前
前端如何让图片、视频、pdf等文件在浏览器直接下载而非预览
前端
cg332 小时前
开源项目自动化:用 GitHub Actions 让每个 Issue 都被温柔以待
前端