通過snmp獲取window資訊,遇到中文為16進制,死活轉換不了。具體資訊如下:
oid為獲取window系統時間:1.3.6.1.2.1.25.1.2.0 = 07:e3:09:0b:15:06:14:06
如上資訊通過以下幾種方法轉換后都為亂碼,包括指定編碼:UTF-8,GBK、GB2312、ISO-8859-1 轉換都為亂碼。
以下幾種嘗試都失敗,那位大神看看如何轉換。
public static String getChinese(String octetString) { //snmp4j遇到中文直接轉成16進制字串
try {
String[] temps = octetString.split(":");
byte[] bs = new byte[temps.length];
for (int i = 0; i < temps.length; i++)
bs[i] = (byte) Integer.parseInt(temps[i], 16);
//GB2312 ISO-8859-1 ASCII
return new String(bs,"GB2312");
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 16進制直接轉換成為字串(無需Unicode解碼)
* @param hexStr
* @return
* @throws UnsupportedEncodingException
*/
public static String hexStr2Str(String hexStr) throws UnsupportedEncodingException {
String str = "0123456789ABCDEF";
char[] hexs = hexStr.toCharArray();
byte[] bytes = new byte[hexStr.length() / 2];
int n;
for (int i = 0; i < bytes.length; i++) {
n = str.indexOf(hexs[2 * i]) * 16;
n += str.indexOf(hexs[2 * i + 1]);
bytes[i] = (byte) (n & 0xff);
}
return new String(bytes);
}
/**
* 16進制轉換成為string型別字串
* @param s
* @return
*/
public static String hexStringToString(String s) {
if (s == null || s.equals("")) {
return null;
}
s = s.replace(" ", "");
byte[] baKeyword = new byte[s.length() / 2];
for (int i = 0; i < baKeyword.length; i++) {
try {
baKeyword[i] = (byte) (0xff & Integer.parseInt(s.substring(i * 2, i * 2 + 2), 16));
} catch (Exception e) {
e.printStackTrace();
}
}
try {
s = new String(baKeyword, "UTF-8");
new String();
} catch (Exception e1) {
e1.printStackTrace();
}
return s;
}
uj5u.com熱心網友回復:
期待大神來解救, 折騰多天,中文亂碼問題未解救.uj5u.com熱心網友回復:
public static String getFormatStr(String octetString){try{
if(!octetString.contains(":")) {
return octetString;
}
String[] temps = octetString.split(":");
byte[] bs = new byte[temps.length];
for(int i=0;i<temps.length;i++)
bs[i] = (byte)Integer.parseInt(temps[i],16);
String encodename=null;
encodename=EncodeUtils.getEncode(new BufferedInputStream( new ByteArrayInputStream(bs)),true);
if (StrUtil.isEmpty(encodename)){
encodename="UTF-8";
}
return new String(bs,encodename);
}catch(Exception e){
return null;
}
}
uj5u.com熱心網友回復:
原因:問題出在SNMP4J的基礎字串類OctetString上。https://blog.csdn.net/lele892207980/article/details/10587647
另外一個人的代碼:
https://my.oschina.net/chengpengvb/blog/3105482
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/20911.html
標籤:Java相關
