Java写对应js的encodeURI,decodeURI方法

| 阅读数:--次| 作者:小豆豆
摘要:Java写对应js的encodeURI,decodeURI方法

java代码
package com.webkfa.test;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;

public class Test {
	public static void main(String[] args){
		System.out.println(urlEncode("蛮好"));
		System.out.println(urlDecode(urlEncode("蛮好"),"gbk"));
	}
	/**
	 * 参数encode
	 * @param old
	 * @return
	 * @throws KoowoHibernateException
	 */
	public static String urlEncode(String old){
		if(old==null){
			return "";
		}
		return URLEncoder.encode(old);
	}
	/**
	 * 参数decode
	 * @param old
	 * @return
	 * @throws KoowoHibernateException
	 */
	public static String urlDecode(String old,String charset){
		if(old==null){
			return "";
		}
		if(charset!=null && !"".equals(charset)){
			try {
				return URLDecoder.decode(old,charset);
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return URLDecoder.decode(old);
	}
}

运行结果
%C2%F9%BA%C3
蛮好
注:网页编码默认是utf-8的,用下面方法要传utf-8
urlDecode("","utf-8")

返回顶部
学到老代码浏览 关闭浏览