首页

关于apache的httpcore源码包EncodingUtils字符编码工具类进行数据字符集编码的转换处理

标签:apache,httpcore,EncodingUtils,字符编码工具类,字符集转换     发布时间:2018-06-25   

一、前言

关于apachehttpcore源码包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@}