标签:
1 String text1 = java.net.URLEncoder.encode("中国" ,"utf-8" ); 2 String text2 = java.net.URLDecoder.decode(text1,"utf-8");
例如,假设你想编码这个string:
pg=q&kl=XX&stype=stext&q=+"Java+I/O"&search.x=38&search.y=3
这段代码对其进行编码:
1 String query = java.net.URLEncoder.encode( "pg=q&kl=XX&stype=stext&q=+"Java+I/O"&search.x=38&search.y=3"); 2 3 System.out.println(query);
不幸的是,得到的输出是:
pg%3Dq%26kl%3DXX%26stype%3Dstext%26q%3D%2B%22Java%2BI%2FO%22%26search.x%3D38%26search.y%3D3
出现这个问题就是方法URLEncoder.encode( ) 在进行盲目地编码。它不能区分在URL或者查询string中被用到的特殊字符(像前面string中的“=”,和“&”)和确实需要被编码的字符。所以URL需要一次只编码一块。
1 private static String _MakeURL(String p_url, Map<String, Object> params) throws UnsupportedEncodingException { 2 StringBuilder url = new StringBuilder(p_url); 3 // Strng.indexOf(substring) //搜索String中的substring,默认从0位开始; 4 5 if(url.indexOf( "?")<0) 6 url.append( ‘?‘); 7 8 for(String name : params.keySet()){ 9 url.append( ‘&‘); 10 url.append(name); 11 url.append( ‘=‘); 12 //url.append(String.valueOf(params.get(name))); 13 //做URLEncoder处理 14 url.append(URLEncoder. encode(String.valueOf (params.get(name)), "UTF-8")); 15 } 16 17 return url.toString().replace( "?&", "?"); 18 }
1 String input = "http://www.altavista.com/cgi-bin/"+"qerry?pg=q&kl=XX&stype=stext&q=%2B%22Java+I%2FO%22&search.x=38&search.y=3"; 2 try { 3 String output = java.net.URLDecoder.decode(input, "UTF-8"); 4 System.out.println(output); 5 }
标签:
原文地址:http://www.cnblogs.com/wufeng0927/p/5335367.html