手头上需要去访问Web Service的一个接口,例如: String Func(String str)。这个接口的参数要求是一个GB2312编码的String。现在的问题是,我构造不出来这样的String。使用getBytes只能得到byte[],而不是String。
String string = "<?xml version=\"1.0\" encoding=\"GB2312\"?><root><author>中文123</author></root>";
//按照 GB2312 Encode编码得到字节
byte[] bytes = string.getBytes("GB2312");但是bytes不能发过来得到GB2312编码的String。比如各种new String构造函数。// 从字节按照 GB2312 Decode解码得到本Java文件相应编码格式字符串。比如本文件是UTF-8格式的,string就是UNICODE。
string = new String(bytes, "GB2312");

解决方案 »

  1.   


    java里面的字符串都是unicode的。java里面只有gb2312的字节数组,没有gb2312的字符串。
      

  2.   


    public static void main(String[] args)throws Exception {
    String str = "中国";
    byte[] buff = str.getBytes("gb2312");
    //这里的gbStr是乱码,但是内容却是gb2312编码格式的字节数组
    String gbStr = new String(buff,"ISO-8859-1");
    System.out.println(gbStr);
    //这里能正常输出“中国”
    System.out.println(new String(gbStr.getBytes("ISO-8859-1"),"gb2312"));
    }
      

  3.   

    感谢GoldFish同学的解答。  
    我的Java文件是UTF-8编码的,是需要ISO-8859-1的Encode+Decode的。
    结贴,谢谢!