关于服务器和浏览器的编码解码

来源:互联网 发布:c语言模拟自动饮料机 编辑:程序博客网 时间:2024/06/07 14:42

对于接受请求:
/*
*获取请求中的编码解码问题 :
*对于post请求,浏览器会根据当前页面的编码来对字符进行编码,所以我们 
*直接采用:
*request.setCharacterEncoding("UTF-8");
*/
//request.setCharacterEncoding("UTF-8");
/*
*对于get请求,浏览器自动对字符进行iso-8859-1编码
*所以我们拿到以后就要对其进行iso-8859-1解码,使其成为原本的字节数组,然后再进行utf-8编码 
*/
Enumeration<String> enums = request.getParameterNames();
while (enums.hasMoreElements()) {
String name = enums.nextElement();
String value = request.getParameter(name);
value = new String(value.getBytes("ISO-8859-1"),"utf-8");
System.out.println(name+":"+value);
}
对于发出相应:
直接使用字节流不指定编码的话,服务器会默认使用系统编码进行编码,浏览器也会使用系统默认编码进行解码
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
OutputStream os = response.getOutputStream();
os.write("我是好人".getBytes());//不指定编码的话将使用系统默认编码
}
=====浏览器正常显示====


使用字节流指定编码,并指定Http协议的相应信息,告诉浏览器用什么编码解析字节流
public void doPost(HttpServletRequest request, HttpServletResponse response)
OutputStream os = response.getOutputStream();
// os.write("我是好人".getBytes());//不指定编码的话将使用系统默认编码
os.write("我也是好人".getBytes("utf-8"));//指定编码,指定编码之后一点要在响应头中指定浏览器解析的编码
//response.setHeader("Content-Type", "text/html;charset=utf-8");
//response.setContentType("text/html;charset=utf-8");
//上述两种都可以
}





字符流:


使用字符流不指定编码的话,服务器会默认使用ISO-8859-1进行编码。
所以如果使用字符流传输汉字,一定要设置编码
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//response.getWriter().write("我是好人");// 不行的,因为默认ISO-8859-1编码
response.setCharacterEncoding("utf-8");//设置成utf-8编码
response.setHeader("Content-Type", "text/html;charset=utf-8");
response.getWriter().write("我是好人");
}


然后setContentType("text/html;charset=编码")有setCharacterEncoding和setHeader("Content-Type", "text/html;charset=编码")的效果
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//response.getWriter().write("我是好人");// 不行的,因为默认ISO-8859-1编码
response.setCharacterEncoding("utf-8");//设置成utf-8编码
response.setHeader("Content-Type", "text/html;charset=utf-8");*/
response.setContentType("text/html;charset=utf-8");//这一句可以达到上面两句的效果
response.getWriter().write("我是好人");
}









0 0
原创粉丝点击