代码之家  ›  专栏  ›  技术社区  ›  Alex R

Unicode问题:如何在HttpClient的响应中转换为?

  •  0
  • Alex R  · 技术社区  · 6 年前

    这个 String s byte[] b 在下面的代码中包含了大致相同事物的不同表示。

    import java.io.UnsupportedEncodingException;
    import java.nio.charset.Charset;
    
    import org.testng.annotations.Test;
    
    public class Utf8Test {
    
        @Test
        public void test() throws UnsupportedEncodingException {
            String s = "’";
            byte[] b = new byte[] { (byte) 0xE2, (byte) 0x80, (byte) 0x99 };
    
            System.out.println(s); // prints ’
    
            String t = new String(b, Charset.forName("UTF-8"));
            System.out.println(t); // prints ’
    
            String u = new String(s.getBytes("ISO-8859-1"), Charset.forName("UTF-8"));
            System.out.println(u); // prints ???
    
            byte[] b2 = new byte[s.length()];
            for(int i=0; i < s.length(); ++i) {
                b2[i] = (byte) (s.charAt(i) & 0xFF);
            }
            String v = new String(b2, Charset.forName("UTF-8"));
            System.out.println(v); // prints ?"
    
            Assert.assertEquals(s,v); // FAIL
        }
    
    }
    

    字符串s 与相同的值 String t ?

    我已经试过代码了 String u String v ,结果将显示在注释中。

    XY问题 这实际上是一个XY问题。这个 字符串s HttpEntity 一个 HttpClient 打电话来。我只想要正确解码的响应。上面的代码要比整个HTTP堆栈容易得多,所以让我们来解决这个问题。

    1 回复  |  直到 6 年前
        1
  •  1
  •   Alex R    6 年前

    这似乎可行,但我不明白为什么,我担心这可能依赖于平台:

    byte[] d = s.getBytes("cp1252"); 
    String w = new String(d, Charset.forName("UTF-8"));
    System.out.println(w); // prints ’