C#如何从UTF8转换成GBK

Python015

C#如何从UTF8转换成GBK,第1张

前提是服务器端只接收gbk编码的请求,这个改不了。那么就要从客户端想办法将utf8编码的xml转成gbk编码的请求。

有以下方法:

1、将xml当中<?xml version="1.0" encoding="UTF-8" standalone="yes"?>改为<?xml version="1.0" encoding="gb2312" standalone="yes"?>

2、在使用HttpWebRequest发送请求时,将utf8的字符串转为gb2312格式的字节数组

System.Text.Encoding gbkEncode = System.Text.Encoding.GetEncoding("gb2312")

byte[] bytes = gbkEncode .GetBytes("要发送的xml字符串")

System.IO.Stream writer = request.GetRequestStream()

writer.Write(bytes, 0, bytes.Length)

ava不同编码之间进行转换,都需要使用unicode作为中转。

以utf-8转gbk为例,示例代码如下:

String t = "这是一个字符串aaa111"

String utf8 = new String(t.getBytes( "UTF-8"))

System.out.println(utf8)

String unicode = new String(utf8.getBytes(),"UTF-8")

System.out.println(unicode)

String gbk = new String(unicode.getBytes("GBK"))

System.out.println(gbk)