java字符串gb18030编码和utf8编码互转[通俗易懂]

java字符串gb18030编码和utf8编码互转[通俗易懂]java字符串gb18030编码和utf8编码互转

大家好,又见面了,我是你们的朋友全栈君。

在做接口联调的时候出现访问对方的时候需要把编码转成gb18030格式的,我这边默认是utf8,这个困扰了很长时间,在网上百度发现大部分字符串转编码都是使用string.getByte(“编码格式”)的方式字节转码,可事实上这样是行不通的。原因有点难说,这里我就说一下可行的方案。

@Test
	public void toObject() throws UnsupportedEncodingException{
		System.out.println("2".equals(null));
		String str = "ab丁亦凝";//编译环境默认是utf8格式
		byte[] bytes = str.getBytes(Charset.forName("GB18030"));//这一步就是转成gb18030格式的字节码
        for (byte b : bytes)  
        {  
            System.out.print(b + " ");  
        }  
        //字节码转成gb18030的字符串
        String str4 = new String(bytes, "GB18030");
        System.out.println(str4);
        System.out.println();  
         
        //再转回utf8
        byte[] bytes4 = str4.getBytes(Charset.forName("UTF-8"));  
        for (byte b : bytes4)  
        {  
            System.out.print(b + " ");  
        }  
        System.out.println();  
        String str44 = new String(bytes4, "UTF-8");  
        System.out.println("---"+str44);//abc你好  
	}

下面再介绍几种其他格式的,其实方式都一样:

@Test
	public void aaa(){
		
		  System.out.println("default charset : "+Charset.defaultCharset());  
	        String str = "abc你好";//string with UTF-8 charset  
	  
	        byte[] bytes = str.getBytes(Charset.forName("UTF-8"));//convert to byte array with UTF-8 encode  
	        for (byte b : bytes)  
	        {  
	            System.out.print(b + " ");  
	        }  
	        System.out.println();  
	        try  
	        {  
	            String str1 = new String(bytes, "UTF-8");//to UTF-8 string  
	            String str2 = new String(bytes, "ISO-8859-1");//to ISO-8859-1 string  
	            String str3 = new String(bytes, "GBK");//to GBK string  
	            String str4 = new String(bytes, "GB18030");
	            System.out.println(str1);//abc你好  
	            System.out.println(str2);//abc??????  
	            System.out.println(str3);//abc浣犲ソ  
	            System.out.println(str4);
	            System.out.println();  
	            byte[] bytes2 = str2.getBytes(Charset.forName("ISO-8859-1"));  
	            for (byte b : bytes2)  
	            {  
	                System.out.print(b + " ");  
	            }  
	            System.out.println();  
	            String str22 = new String(bytes2, "UTF-8");  
	            System.out.println(str22);//abc你好  
	              
	            System.out.println();  
	            byte[] bytes3 = str3.getBytes(Charset.forName("GBK"));  
	            for (byte b : bytes3)  
	            {  
	                System.out.print(b + " ");  
	            }  
	            System.out.println();  
	            String str33 = new String(bytes3, "UTF-8");  
	            
	            byte[] bytes4 = str4.getBytes(Charset.forName("GB18030"));  
	            for (byte b : bytes4)  
	            {  
	                System.out.print(b + " ");  
	            }  
	            System.out.println();  
	            String str44 = new String(bytes4, "UTF-8");  
	            System.out.println("---"+str44);//abc你好  
	        } catch (UnsupportedEncodingException e)  
	        {  
	            e.printStackTrace();  
	        }  
	}

最后在联调接口通讯中,注意两点:

1,在最终传输的字节数组中修改编码,

2,对方返回的信息,要先使用对方编码转成字符串,再转成自己需要的编码

在下面的例子中有讲解:

private String sendReq(Object req) throws Exception {
        String reqXml =  XStreamHandler.toXml(req);
        //加入报文头
        reqXml=HEADER+reqXml;
        //计算报文长度
		int len=reqXml.getBytes().length;
		String bodyStr = String.format("%04d", len);
		//加入报文长度
		reqXml=bodyStr+reqXml;
		//utf8转gb18030  下面两行就是多余的,因为不是最终修改编码的位置
		byte[] bytes = reqXml.getBytes(Charset.forName("GB18030"));
		reqXml = new String(bytes, "GB18030");
		logger.info("组装好的最终报文是:"+reqXml);
		YakMessage msg = new YakMessage();
		ByteBuffer buffer = ByteBuffer.allocate(reqXml.getBytes().length);
		buffer.put(reqXml.getBytes(Charset.forName("GB18030"))); //这里才是有用的,因为参数传递最终还是在io流中以字节格式传输的
		//设置YakMessage
		msg.setRawMessage(buffer.array());
		buffer.clear();
		//发送请求
		YakMessage response = FBHYShortTermSocketClient.write(msg);
		String respXml = new String(response.getRawMessage(),Charset.forName("GB18030"));//这里对面返回的文字编码是GB18030,
		//gb18030转utf8
		byte[] bytes2 = respXml.getBytes(Charset.forName("UTF-8"));  
	    respXml = new String(bytes2, "UTF-8");
		return respXml;
	}

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/106078.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • django 视图_基本视图有哪些

    django 视图_基本视图有哪些视图家族drf的视图总共分为以下4个,对应4个源码文件views:视图类generics:工具视图mixins:视图工具集viewsets:视图集学习曲线我们学习视图,可以按照以下的曲线

    2022年7月30日
    7
  • MyEclipse SVN插件的安装详解[通俗易懂]

    MyEclipse SVN插件的安装详解[通俗易懂]一、安装类型(一)、在线安装1.打开Myeclipse,在菜单栏中选择Help→SoftwareUpdates→FindandInstall;2.选择Searchfornewfeaturestoinstall,点击Next进入下一步;

    2022年7月20日
    13
  • freeswitch呼叫中心开发

    freeswitch呼叫中心开发开发freeswitch呼叫中心1、配置ivr2、启用mod_callcenter3、开发websocker接口,通过esl接口,发送callcenter_config命令给fs4、开发客户端页面,注册,注销,就绪,置忙等接口5、开发来电弹屏,通过客户端读取redis参数实现freeswitch的呼叫中心模块很方便的就可以让用户体验这种呼叫中心模式,包含了很多功能,具体参数的配置在使用中自行摸索。编译安装freeswitch时需要开启mod_callcenter、mod_fifo的编译,之

    2022年7月12日
    19
  • 数据库课程设计-宿舍管理系统「建议收藏」

    数据库课程设计-宿舍管理系统「建议收藏」最近写完了数据库的课程设计,想把整个源码的编辑过程发出来。程序很简单,需要有很多完善的地方,在这里,我想和大家分享写这个程序的心路历程。首先,在开始写程序之前。我们需要先写一些工具类,来辅助完成整个程序的构建,在这里我把连接jdbc的代码放在了一个包下面。如下图:在这里我们先来写最基本的类,jdbcDrive,这是负责和数据库进行连接,并且执行语句的类publ…

    2022年5月19日
    31
  • android listview 滚动到底部

    android listview 滚动到底部androidlistview滚动到底部,亲试有效:listView.setSelection(ListView.FOCUS_DOWN);//刷新到底部。注意:调用完了,不要调用listView.invalidateViews();

    2022年7月17日
    13
  • epoll高度封装reactor,几乎所有可见服务器的底层框架「建议收藏」

    epoll高度封装reactor,几乎所有可见服务器的底层框架「建议收藏」epoll高度封装reactor,几乎所有可见服务器的底层框架

    2025年6月17日
    2

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号