URLEncoder and JavaScript encodeURIComponent

本文探讨了服务器端和客户端在字符串编码上的不同方式,指出差异导致的问题,并提供了一个简化认证变化的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

URLEncoder and JavaScript encodeURIComponent

Recently our system ran into a trouble about authentication. So I dive into the implementation we did in auth. I take part to design that, but I am not 100% know about the implementation.

After investigation, I found the problem.

The issue is coming from the way server side and client side encoding the string, not about the “special” characters.

        I just read the server side source codes, I just know that we are using java.net.URLEncoder from JDK to do the encoding. Doc is here for references: http://docs.oracle.com/javase/1.5.0/docs/api/java/net/URLEncoder.html

        And the client JS side is using encodeURLComponent() which is Similar. Doc is here for references: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent

        So here comes the problem, the 2 encoding ways are similar, not exactly the same. The difference characters are ~'()! and "+. We need to do something like this in server side or client side if we want to keep the auth changes as small as possible:


public static String encodeURIComponent(String component) {
String result = null;
 
try {
result = URLEncoder.encode(component, "UTF-8")
.replaceAll("\\%28", "(")
.replaceAll("\\%29", ")")
.replaceAll("\\+", "%20")
.replaceAll("\\%27", "'")
.replaceAll("\\%21", "!")
.replaceAll("\\%7E", "~");
} catch (UnsupportedEncodingException e) {
result = component;
}
 
return result;


By the way, why we need encoding for our string, because we do calculate query string in URL and post body. We just want to make sure it is the same thing after server side receive the query string in URL and post body.


References:
https://gist.github.com/declanqian/7892516
http://stackoverflow.com/questions/607176/java-equivalent-to-javascripts-encodeuricomponent-that-produces-identical-outpu
http://www.technicaladvices.com/2012/02/20/java-encoding-similiar-to-javascript-encodeuricomponent/

JS Doc
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent

Java Doc
http://docs.oracle.com/javase/1.5.0/docs/api/java/net/URLEncoder.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值