如何UTF-8编码一个字符串? [英] How to UTF-8 encode a string?

查看:72
本文介绍了如何UTF-8编码一个字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



你好,

我正在按照以下方式进行utf-8编码。

字符串消息;
< br $>
UTF8Encoding utf8 = new UTF8Encoding();


Byte [] encodedBytes = utf8.GetBytes(message);


message = encodedBytes.ToString();


有人可以纠正我吗?


非常感谢


JJ

解决方案

jens Jensen写道:

你好,
我在做utf-8编码方式如下。
字符串消息;

UTF8Encoding utf8 = new UTF8Encoding();


请注意,您可以使用Encoding.UTF8Encoding来避免每次都创建一个新的

实例。

Byte [] encodedBytes = utf8.GetBytes(消息);
message = encodedBytes.ToString();

有人可以纠正我吗?




嗯,你期待的消息是什么? .NET中的所有字符串都是

UTF-16编码。没有办法解决这个问题(并且它确实不是一个问题)。


你能给我们更多的背景吗?当您想要将文本表示转换为文本的二进制表示时,通常需要编码 - 例如,例如
将一些文本写入流。你想在这里做什么?
在这里做什么?


Jon


>你能给我们更多的背景吗?当

想要从文本表示转换为文本的二进制表示时,通常需要编码 - 例如将一些文本写入流。你想在这做什么?

Jon




我Jon,

我需要通过HTTP POST将数据发布到Web服务。


webservice需要utf-8编码数据。我的POST目前因此而失败




非常感谢

JJ


jens Jensen写道:

你能给我们更多的背景吗?当您想要从文本表示转换为文本的二进制表示时,通常需要编码 - 例如将一些文本写入流。你想在这做什么?



我Jon,
我需要将数据发布到HTTP服务的网络服务。
Web服务需要utf-8编码数据。我的POST因此而失败




对。所以,你需要像你一样获取字节,然后将那些

写入请求流。


Jon



hello,
i''m doing utf-8 encoding the following way.
string message;

UTF8Encoding utf8 = new UTF8Encoding();

Byte[] encodedBytes = utf8.GetBytes(message);

message = encodedBytes.ToString();

can someone correct me?

many thanks

JJ

解决方案

jens Jensen wrote:

hello,
i''m doing utf-8 encoding the following way.
string message;

UTF8Encoding utf8 = new UTF8Encoding();
Note that you can use Encoding.UTF8Encoding to avoid creating a new
instance each time.
Byte[] encodedBytes = utf8.GetBytes(message);
message = encodedBytes.ToString();

can someone correct me?



Well, what are you expecting message to be? All strings in .NET are
UTF-16 encoded. There''s no way round that (and it''s not really a
problem).

Could you give us more context? Normally encoding is required when you
want to convert from a text representation to a binary represenation of
that text - e.g. to write some text to a stream. What are you trying to
do here?

Jon


> Could you give us more context? Normally encoding is required when you

want to convert from a text representation to a binary represenation of
that text - e.g. to write some text to a stream. What are you trying to
do here?

Jon



I Jon,
I need to post data to web service vis HTTP POST.

The webservice requires utf-8 encoded data. My "POST" is currently failing
due to this.

Many thanks
JJ


jens Jensen wrote:

Could you give us more context? Normally encoding is required when you
want to convert from a text representation to a binary represenation of
that text - e.g. to write some text to a stream. What are you trying to
do here?



I Jon,
I need to post data to web service vis HTTP POST.

The webservice requires utf-8 encoded data. My "POST" is currently failing
due to this.



Right. So, you need to get the bytes as you did, and then write those
to the request stream.

Jon


这篇关于如何UTF-8编码一个字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆