URL编码ASCII / UTF16字符 [英] URL encode ASCII/UTF16 characters

查看:170
本文介绍了URL编码ASCII / UTF16字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图URL编码一些字符串,但我有一个由.NET Framework提供的方法问题。

I'm trying to URL-encode some strings, however I have problems with methods provided by the .Net framework.

比如说,我想的包含A字符编码字符串。据 W3Schools的比如说,我希望这个卡拉科特编码为%E2' (和PHP系统我必须调用预计,太...)

For instance, I'm trying the encode strings that contain the 'â' character. According to w3schools for instance, I would expect this caracter to be encoded as '%E2' (and a PHP system I must call expects this too...).

我尝试使用以下方法:

System.Web.HttpUtility.UrlEncode("â");
System.Web.HttpUtility.UrlPathEncode("â");
Uri.EscapeUriString("â");
Uri.EscapeDataString("â");



不过,他们都编码这个字符为:
%C3%A2

However, they all encode this character as: %C3%A2

我想这事做的事实,在.net中的字符串是UTF-16编码。因此,为了避免这个问题,我可以这样写,例如:

I suppose this has something to do with the fact that strings in .Net are UTF-16 encoded. So to avoid this problem, I can write this for instance:

"%" + ((int)character).ToString("X")

不过,我想知道,如果框架已经有一个内置的方法(我不能在这里或其他地方,为什么我的性格编码这种方式找到任何答案)?

However, I would like to know if the framework already has a built-in method (I can't find any answer here or elsewhere as to why my character is encoded this way)?

推荐答案

的原因是的的是.NET使用UTF-16编码字符串。其原因是, 以UrlEncode(字符串)超载通过默认使用UTF-8,和%C3%A2 是正确的UTF-8编码 A

The reason is not that .NET uses UTF-16 encoded strings. The reason is that the UrlEncode(string) overload uses UTF-8 by default, and %C3%A2 is the correct UTF-8 encoding of â:

HttpUtility.UrlEncode方法默认使用UTF-8编码。因此,使用以UrlEncode方法提供相同的结果与使用以UrlEncode方法并指定UTF8作为第二个参数。

The HttpUtility.UrlEncode method uses UTF-8 encoding by default. Therefore, using the UrlEncode method provides the same results as using the UrlEncode method and specifying UTF8 as the second parameter.

如果你喜欢一个不同的编码(例如 Latin-1的或代码页1252,其中 A 对应%E2 ),你可以使用另一个重载允许您指定的编码:

If you prefer a different encoding (for example Latin-1 or Codepage 1252, where â corresponds to %E2), you can use another overload that allows you to specify an encoding:

var x = HttpUtility.UrlEncode("â", Encoding.GetEncoding(1252));

这篇关于URL编码ASCII / UTF16字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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