1. 程式人生 > >Url編碼與解碼

Url編碼與解碼

package charset;

import java.io.UnsupportedEncodingException;

import org.apache.commons.codec.CharEncoding;

import org.apache.commons.codec.DecoderException;

import org.apache.commons.codec.net.URLCodec;

public class EncoderUtil {

/** url codec. */

private static final URLCodec URL_CODEC = new URLCodec();

/**

* url

encode, default charset utf-8

* @param url url

* @return encode值

*/

public static String urlEncode(String url) {

try {

return urlEncode(url, CharEncoding.UTF_8);

} catch (Exception e) {

}

return null;

}

/**

* url encode

* @param url encode值

* @return

*/

public static String urlEncode(String url, String charset) {

try {

return URL_CODEC.encode(url, charset);

} catch (Exception e) {

}

return null;

}

public static String urlDecoder(String url){

return urlDecoder(url,CharEncoding.UTF_8);

}

/**

* 對url進行解碼

* @param url

* @return

*/

public static String urlDecoder(String url, String charset){

try {

return URL_CODEC.decode(url, charset);

} catch

(UnsupportedEncodingException e) {

} catch (DecoderException e) {

}

return null;

}

public static void main(String[] args){

String url="https://www.baidu.com/id={0}";

String encoder=urlEncode(url);

System.out.println(encoder);

String decoder=urlDecoder(encoder);

System.out.println(decoder);

}

}