<dependency>
<groupId>com.googlecode.juniversalchardet</groupId>
<artifactId>juniversalchardet</artifactId>
<version>1.0.3</version>
</dependency>
//判斷byte編碼類型
public static String getEncoding(byte[] bytes) {
String DEFAULT_ENCODING = "UTF-8";
UniversalDetector detector =new UniversalDetector(null);
detector.handleData(bytes, 0, bytes.length);
detector.dataEnd();
String encoding = detector.getDetectedCharset();
detector.reset();
if (encoding == null) {
encoding = DEFAULT_ENCODING;
}
return encoding;
}
//此處為http獲取到的bytes
byte[] bytes = new httppost().getdata(url,null);
String encoding = Tools.getEncoding(bytes);//編碼判斷
try {
if(encoding.indexOf("GB")>=0){//由於GBK編碼有多種,此處這樣判斷即可
result = new String(bytes,"gbk");
}
if("UTF-8".equals(encoding)) {
result = new String(bytes, "utf-8");
}
} catch (UnsupportedEncodingException e) {
System.out.println("抓取新ERP櫃子數量編碼失敗");
e.printStackTrace();
}