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

相关推荐
遇到困难睡大觉哈哈21 小时前
Harmony os 静态卡片(ArkTS + FormLink)详细介绍
前端·microsoft·harmonyos·鸿蒙
用户47949283569151 天前
Bun 卖身 Anthropic!尤雨溪神吐槽:OpenAI 你需要工具链吗?
前端·openai·bun
p***43481 天前
前端在移动端中的网络请求优化
前端
g***B7381 天前
前端在移动端中的Ionic
前端
拿破轮1 天前
使用通义灵码解决复杂正则表达式替换字符串的问题.
java·服务器·前端
whltaoin1 天前
【 Web认证 】Cookie、Session 与 JWT Token:Web 认证机制的原理、实现与对比
前端·web·jwt·cookie·session·认证机制
Aerelin1 天前
爬虫playwright入门讲解
前端·javascript·html·playwright
5***o5001 天前
前端在移动端中的NativeBase
前端
灵魂学者1 天前
Vue3.x —— 父子通信
前端·javascript·vue.js·github
1***Q7841 天前
前端跨域解决方案
前端