一、前言
关于apache的httpcore源码包org.apache.http.util.EncodingUtils字符集编码工具类,实现二进制数据byte[]进行设置编码集转为字符串、字符串数据返回对应字符集为二进制数据byte[]、获取getAsciiBytes字符串为ascii二进制数据、将二进制数据byte[]的转为ascii编码字符集等。
二、源码说明
package org.apache.http.util;@b@@b@import java.io.UnsupportedEncodingException;@b@@b@public final class EncodingUtils@b@{@b@ public static String getString(byte[] data, int offset, int length, String charset)@b@ {@b@ if (data == null) {@b@ throw new IllegalArgumentException("Parameter may not be null");@b@ }@b@@b@ if ((charset == null) || (charset.length() == 0))@b@ throw new IllegalArgumentException("charset may not be null or empty");@b@@b@ try@b@ {@b@ return new String(data, offset, length, charset); } catch (UnsupportedEncodingException e) {@b@ }@b@ return new String(data, offset, length);@b@ }@b@@b@ public static String getString(byte[] data, String charset)@b@ {@b@ if (data == null)@b@ throw new IllegalArgumentException("Parameter may not be null");@b@@b@ return getString(data, 0, data.length, charset);@b@ }@b@@b@ public static byte[] getBytes(String data, String charset)@b@ {@b@ if (data == null) {@b@ throw new IllegalArgumentException("data may not be null");@b@ }@b@@b@ if ((charset == null) || (charset.length() == 0))@b@ throw new IllegalArgumentException("charset may not be null or empty");@b@@b@ try@b@ {@b@ return data.getBytes(charset); } catch (UnsupportedEncodingException e) {@b@ }@b@ return data.getBytes();@b@ }@b@@b@ public static byte[] getAsciiBytes(String data)@b@ {@b@ if (data == null)@b@ throw new IllegalArgumentException("Parameter may not be null");@b@@b@ try@b@ {@b@ return data.getBytes("US-ASCII");@b@ } catch (UnsupportedEncodingException e) {@b@ throw new Error("HttpClient requires ASCII support");@b@ }@b@ }@b@@b@ public static String getAsciiString(byte[] data, int offset, int length)@b@ {@b@ if (data == null)@b@ throw new IllegalArgumentException("Parameter may not be null");@b@@b@ try@b@ {@b@ return new String(data, offset, length, "US-ASCII");@b@ } catch (UnsupportedEncodingException e) {@b@ throw new Error("HttpClient requires ASCII support");@b@ }@b@ }@b@@b@ public static String getAsciiString(byte[] data)@b@ {@b@ if (data == null)@b@ throw new IllegalArgumentException("Parameter may not be null");@b@@b@ return getAsciiString(data, 0, data.length);@b@ }@b@}