c# - URI 编码奇怪

标签 c#

这与另一个 open question of mine 有关。虽然没有任何实际答案,但 dtb 引导我沿着这条路走下去,所以如果它有成果,我会接受他的答案。

我正在用一些(相当复杂的)C# 代码为 BitTorrent 跟踪器生成一个公告 url。

最终结果是这样的:

http://208.106.250.207:8192/announce?info_hash=-%CA8%C1%C9rDb%ADL%ED%B4%2A%15i%80Z%B8%F%C&peer_id=01234567890123456789&port=6881&uploaded=0&downloaded=0&left=0&compact=0&no_peer_id=0&event=started

If I copy paste this into an address bar, I get a valid response from the tracker. However, my code is getting an error message back (invalid info_hash).

The code dispatching the request:

... Code building the URI ...
String uri = BuildURI(); //This results in the above URI string.
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(uri);
req.Proxy = new WebProxy();  //Some examples online suggest this is required, so WARNING: here be voodoo (determine if necessary later)
WebResponse resp = req.GetResponse();
Stream stream = resp.GetResponseStream();
... Code parsing the stream ...

如果我调试并提取 req.RequestUri 的字符串版本,我得到:

http://208.106.250.207:8192/announce?info_hash=-Ê8ÁÉrDb­Lí´*iZ¸%25F%25C&peer_id=01234567890123456789&port=6881&uploaded=0&downloaded=0&left=0&compact=0&no_peer_id=0&event=started

我实际上无法分辨“在线”发送到跟踪器的内容,但看起来我在对 URI 做一些愚蠢的事情。有人知道吗?

最佳答案

使用 System.Uri 中的 .AbsoluteUri(作为 Request.RequestUri 的类型)获取您的原始 url 而不会被“修改”

这里的“问题”是 .Net System.Uri 类的工作方式(我在引号中说“问题”,因为它实际上行为正确)。

您的原始 info_hash 查询字符串是一堆 url 编码字节。当您使用 Uri.ToString() 检索 Uri 实例时,它有助于解码这些(通过进行 url 解码)并将这些字节(例如 %CA)转换为它们各自的字符(在您的情况下为 Ê,但这可能取决于您的本地代码页设置,因为这是一个“上半部分”ANSI 字符,并且会根据代码页而改变)。

在内部,查询字符串实际上被正确存储; System.Uri 类只是想提供帮助。

这段代码应该能更好地说明它:

 string myUrl = "http://208.106.250.207:8192/announce?info_hash=-%CA8%C1%C9rDb%ADL%ED%B4%2A%15i%80Z%B8%F%C&peer_id=01234567890123456789&port=6881&uploaded=0&downloaded=0&left=0&compact=0&no_peer_id=0&event=started";

            Uri myUri = new Uri(myUrl);
            Console.WriteLine("ToString: " + myUri.ToString());
            Console.WriteLine("Query: " + myUri.Query);
            Console.WriteLine("AbsoluteUri: " + myUri.AbsoluteUri);

我猜,在线路上,一切都很好,这只是您如何从 System.Uri 检索 url 的产物。

关于c# - URI 编码奇怪,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1105244/

相关文章:

c# - 具有内置审计跟踪的 ORM

c# - 为类分配数值

c# - 对二维数组中的每个元素执行一个操作

c# - 在 CurrentItemChanged 上将文本框的内容设置为大写

c# - 在不直接更改 SelectedIndex 的情况下设置 ComboBox 默认值

c# - 下载前检查文件在ftp服务器上是否存在

c# - LINQ 中的日期格式

c# - 绑定(bind) EasingColorKeyframe 值

c# - Jwt 代码不适用于 .NET Core 2

c# - 检查 SetParent 函数是否有效?