gpt4 book ai didi

java - 我可以使用正文以外的编码发送 POST 表单吗?

转载 作者:行者123 更新时间:2023-11-30 05:12:48 24 4
gpt4 key购买 nike

我有一个 HTML 页面,如下所示:

<HTML>
<meta http-equiv='Content-Type' content='text/html; charset=gb2312'>
<BODY onload='document.forms[0].submit();'>
<form name="form" method="post" action="/path/to/some/servlet">
<input type="hidden" name="username" value="麗安"> <!-- UTF-8 characters -->
</form>
</BODY>
</HTML>

如您所见,此页面的内容是 UTF-8,但我需要使用 GB2312 字符编码发送它,因为我发送此页面的 servlet 期望我使用 GB2312。

这是一个有效的场景吗?因为在 servlet 中,我无法使用将字符编码设置为 GB2312 的过滤器来检索这些汉字!

我创建了一个示例 Servlet:

package org.daz;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class EncodingServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final String ENCODING = "GB2312";

protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

setCharacterEncoding(request, response);

String username = request.getParameter("username");
System.out.println(username);

}

private void setCharacterEncoding(HttpServletRequest request, HttpServletResponse response)throws IOException{
request.setCharacterEncoding(ENCODING);
response.setCharacterEncoding(ENCODING);
}

}

输出为:楹��

最佳答案

这是不可能的。您需要从一开始就使用 GB2312 字符,或者将整个应用程序更改为仅使用 UTF-8。您无法通过这种方式从字符编码 X 转换为字符编码 Y。任何超出 ASCII 范围的字符都可能被损坏。

正如一些人所建议的,表单的 accept-charset 属性被大多数网络浏览器忽略。 W3 spec也按字面意思表示“用户代理可以解释..”,而不是“必须”。即使如此,它也只会用于对实际用户输入进行编码,而不是像您的示例中那样对隐藏字段进行编码。它们已经以页面自己的编码(在本例中为 GB2312)进行编码。换句话说,这些 UTF-8 字符在浏览器处理页面时已经被损坏。

关于java - 我可以使用正文以外的编码发送 POST 表单吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2776990/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com