Showing posts with label Urlencode. Show all posts
Showing posts with label Urlencode. Show all posts

Tuesday, February 03, 2009

urlencode and urldecode in java

import java.net.URLDecoder;
import java.net.URLEncoder;

import junit.framework.TestCase;

public class URLEncodeAndDecode extends TestCase {

public void testUrlEncode() throws Exception {
String str = "中文";
String utf8Code = URLEncoder.encode(str, "UTF-8");
assertEquals("%E4%B8%AD%E6%96%87", utf8Code);
String gbkCode = URLEncoder.encode(str, "GBK");
assertEquals("%D6%D0%CE%C4", gbkCode);

assertEquals("中文", URLDecoder.decode("%E4%B8%AD%E6%96%87", "UTF-8"));
assertEquals("中文", URLDecoder.decode("%D6%D0%CE%C4", "GBK"));
}

}

Thursday, April 17, 2008

还原apache访问日志中的URL查询字符串

当IE在访问URL:
http://localhost/a.html?q=中文
在apache日志里能看到以下内容:
GET /a.html?q=\xd6\xd0\xce\xc4 HTTP/1.1

而在Firefox中访问相同URL:
日志中看到的内容是对字符串进行urlencode过后的格式:
GET /a.html?q=%D6%D0%CE%C4 HTTP/1.1

现在IE下,\xXX这种看上像2位16进制值XX指定的1个字符(可能是Latin-1字符集的字符),如果想直接还原出“中文”2个字比较困难。
不过在与Firefox中的日志对比之下,能看出只要直接将\x替换成%,然后用PHP的urldecode反解析就能得到对应的字符串。

另外说明一点:
这个例子中看到的值%D6%D0%CE%C4,是按gbk字符集进行urlencode计算得到的对应值,如果urldecode反解析得到是乱码,则日志记录的应该是utf-8格式的urlencode值,用PHP的iconv函数处理一下。