各种格式的编码解码工具类分享(hex解码 base64编码)
import java.io.unsupportedencodingexception;
import java.net.urldecoder;
import java.net.urlencoder;
import org.apache.commons.codec.decoderexception;
import org.apache.commons.codec.binary.base64;
import org.apache.commons.codec.binary.hex;
import org.apache.commons.lang.stringescapeutils;
/**
* 各种格式的编码加码工具类.
*
* 集成commons-codec,commons-lang及jdk提供的编解码方法.
*
*
*/
public class encodeutils {
private static final string default_url_encoding = "utf-8";
/**
* hex编码.
*/
/*public static string hexencode(byte[] input) {
return hex.encodehexstring(input);
}*/
/**
* hex解码.
*/
public static byte[] hexdecode(string input) {
try {
return hex.decodehex(input.tochararray());
} catch (decoderexception e) {
throw new illegalstateexception("hex decoder exception", e);
}
}
/**
* base64编码.
*/
public static string base64encode(byte[] input) {
return new string(base64.encodebase64(input));
}
/**
* base64编码, url安全(将base64中的url非法字符�?,/=转为其他字符, 见rfc3548).
*/
public static string base64urlsafeencode(byte[] input) {
return base64.encodebase64urlsafestring(input);
}
/**
* base64解码.
*/
public static byte[] base64decode(string input) {
return base64.decodebase64(input);
}
/**
* url 编码, encode默认为utf-8.
*/
public static string urlencode(string input) {
try {
return urlencoder.encode(input, default_url_encoding);
} catch (unsupportedencodingexception e) {
throw new illegalargumentexception("unsupported encoding exception", e);
}
}
/**
* url 解码, encode默认为utf-8.
*/
public static string urldecode(string input) {
try {
return urldecoder.decode(input, default_url_encoding);
} catch (unsupportedencodingexception e) {
throw new illegalargumentexception("unsupported encoding exception", e);
}
}
/**
* html 转码.
*/
public static string htmlescape(string html) {
return stringescapeutils.escapehtml(html);
}
/**
* html 解码.
*/
public static string htmlunescape(string htmlescaped) {
return stringescapeutils.unescapehtml(htmlescaped);
}
/**
* xml 转码.
*/
public static string xmlescape(string xml) {
return stringescapeutils.escapexml(xml);
}
/**
* xml 解码.
*/
public static string xmlunescape(string xmlescaped) {
return stringescapeutils.unescapexml(xmlescaped);
}
}
上一篇: Android AsyncTask用法巧用实例代码
下一篇: Android侧滑导航栏的实例代码