您的位置:首页 > 理论基础 > 计算机网络

http发送数据的解码与编码

2012-11-19 14:54 204 查看
假设url为:http://localhost:8080/RestTest/中/1?username=中

1.一般情况下,url中目录中的中文按照utf-8进行编码,“中”的utf-8编码为“%E4%B8%AD”。

2.get方法的参数按照计算机的系统语言进行编码,中文按照GBK,“中”的GBK编码为“%D6%D0”;日文环境按照“shift-jis”,“中”的编码为“%92%86”

3.post方式的参数,会放到http正文当中,按照jsp页面中的content-type编码。

针对一个在后台的解码:

1.假如在后台中的匹配路径中含有中文,那么要将路径中的中文“中”按照正确的格式解码,解决方案可也是:

在tomcat的server.xml的Connector节点下加入URIEncoding="utf-8",这样就能匹配到中文的路径。

一般在路径中不会包含中文,另外在tomcat中加入URIEncoding="utf-8",会影响所有的工程,所以这种方法一般不会使用(本人基于兴趣看了下)。

2.对get参数进行正确的解码。

在tomcat中没有加入URIEncoding="utf-8",tomcat默认按照iso-8859-1解码,所以要想得到正确的中文参数,按如下方式,先解码再按照正确方式编码:

System.out.println(new String(request.getParameter("username").getBytes("iso-8859-1"),"参数编码"));

参数编码是自己计算机系统环境的编码。

如果加入URIEncoding="utf-8",理论上参数也会按照utf-8进行解码,GBK编码的D6D0在utf-8中不对应“中”字,或许会出现别的字符,所以参数对应的二进制发生改变,所以在后面不管怎么编码与解码都会出现错误:

System.out.println(new String(request.getParameter("username").getBytes("utf-8"),"参数编码"));

System.out.println(new String(request.getParameter("username").getBytes("iso-8859-1"),"参数编码"));

现在还没解决掉,望大家帮忙。

在实验过程中,路径下的中文和参数中的中文采用了不同的编码,我们可以采用javascript来对参数进行编码,因为encodeURI()方法会将参数按照utf-8编码,所以可以利用ajax来实现(这只是一种解决方法,研究着玩,有兴趣的可以试试)。

<script language="javascript" type="text/javascript">
var request = false;
try {
request = new XMLHttpRequest();
} catch (trymicrosoft) {
try {
request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (othermicrosoft) {
try {
request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (failed) {
request = false;
}
}
}

if (!request)
alert("Error initializing XMLHttpRequest!");

function getCustomerInfo() {
var username = document.getElementById("username").value;
alert(username);
var url =encodeURI("../students/1?username="+username);
request.open("GET",url,true);
request.send(null);
}
alert("sdfsdf");
</script>


这样的话,username=中,“中”就会按照utf-8编码,从而避免了直接表单提交时采用的系统编码,中文系统编码为gbk,日文是shift-jis。

3.post方式的解码 URIEncoding="utf-8"的设置对post没有影响,所以post参数在后台还是按照iso-8859-1来进行解码的:

String s = new String(t.getParameter("username").getBytes("ISO-8859-1"),"utf-8");

这样就能输出中文。

如果不想每次都这么转换,在spring中可以使用filter来进行。filter对post起作用,对get不起作用。

<filter>

<filter-name>encodingFilter</filter-name>

<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>

<init-param>

<param-name>encoding</param-name>

<param-value>utf-8</param-value>

</init-param>

</filter>

<filter-mapping>

<filter-name>encodingFilter</filter-name>

<servlet-name>rest</servlet-name>

</filter-mapping>

System.out.println(t.getParameter("username"));

也可以自己写过滤器,但是不推荐,因为自己写和使用现有的是一样的,没那个必要。

暂时先写这么多,把自己的学习记录下,上面还有没解决的问题,望大家指导下,感激不尽!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: