2014-04-22 74 views
0

我得到的HTML JavaScript字符串,如:如何解码为UTF-8字符串从十六进制编码字符串

htmlString = "https\x3a\x2f\x2ftest.com" 

但我想下面将其解码:

str = "https://test.com" 

这意味着,我想要一个Util API:

public static String decodeHex(String htmlString){ 
    // do decode and converter here 
} 

public static void main(String ...args){ 
     String htmlString = "https\x3a\x2f\x2ftest.com"; 
     String str = decodeHex(htmlString); 
     // str should be "https://test.com" 
} 

有没有人知道如何实现这个API - decodeHex?

+0

http://ddecode.com/hexdecoder/是好的,但我想一个Java API来实现相同的功能。 –

回答

1

这应该足以让你开始。我离开实施hexDecode并将错误的输入作为练习来排序。

public String decode(String encoded) { 
    StringBuilder sb = new StringBuilder(); 
    for (int i = 0; i < encoded.length(); i++) { 
    if (encoded.charAt(i) == '\' && (i + 3) < encoded.length() && encoded.charAt(i + 1) == 'x') { 
     sb.append(hexDecode(encoded.substring(i + 2, i + 4))); 
     i += 3; 
    } else { 
     sb.append(encoded.charAt(i)); 
    } 
    } 
    return sb.toString; 
} 
0
public String decode(String encoded) throws DecoderException { 
     StringBuilder sb = new StringBuilder(); 
     for (int i = 0; i < encoded.length(); i++) { 
     if (encoded.charAt(i) == '\\' && (i + 3) < encoded.length() && encoded.charAt(i + 1) == 'x') { 
      sb.append(new String(Hex.decodeHex(encoded.substring(i + 2, i + 4).toCharArray()),StandardCharsets.UTF_8)); 
      i += 3; 
     } else { 
      sb.append(encoded.charAt(i)); 
     } 
     } 
     return sb.toString(); 
    } 
相关问题