.Net转Java自学之路—基础巩固篇二十六(编码)

编码:

  常见的字符编码:iso-8859-1(不支持中文)、gb2312、gbk、utf-8 等。

  1、响应编码:

    当使用response.getWriter()来向客户端发送字节数据时,若在之前没有设置编码,那么默认使用iso,iso不支持中文,故一定乱码。

    在使用response.getWriter()之前可以使用response.setCharacterEncoding("utf-8")来设置字符流的编码。即response.getWriter()这个字符流,发送的字符都是用设置的编码。

    服务器可以使用setHeader()来设置名为Content-Type的响应头。response.setHeader("Content-Type","text/html;charset=utf-8")这个方法,不只是设置响应头,而且会设置setCharacterEncoding()

    response的设置Content-Type头还有一个便捷方法:response.setContentType("text/html;charset=utf-8");

  2、请求编码:

    客户端向服务器端传递了设置编码的参数数据,服务器tomcat默认设用iso来处理参数。

    post请求:

      只需要在获取参数之前调用response.setCharacterEncoding("utf-8");设置编码后再获取参数。

    get请求:

      需要反编译。先获取参数数据。然后进行

      byte[] bytes=str.getBytes("iso-8859-1");

      str=new String(bytes,"utf-8");

  3、URL编码:

    表单的类型:Content-Type:application/x-www-form-urlencoded

      它不是字符编码;是用来在客户端与服务器之间传递参数用的一种方式;URL编码需要先指定一种字符编码,把字符串解码后,得到byte[],然后把小于0的字节+256,再转换成16进制,前加% 。

      post请求默认使用URL编码,tomcat会自动使用URL编码。

      URL编码:String str=URLEncoder.encode(str,"utf-8");

      URL解码:String str=URLDecoder.decode(str,"utf-8");

猜你喜欢

转载自www.cnblogs.com/drop/p/10388266.html