C# “无法确定 URI 的格式”与 WebRequest

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/906932/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 02:32:29  来源:igfitidea点击:

"The format of the URI could not be determined" with WebRequest

c#exceptionhttpwebrequest

提问by Frode Lillerud

I'm trying to perform a POST to a site using a WebRequest in C#. The site I'm posting to is an SMS site, and the messagetext is part of the URL. To avoid spaces in the URL I'm calling HttpUtility.Encode() to URL encode it.

我正在尝试使用 C# 中的 WebRequest 对站点执行 POST。我发布到的站点是一个 SMS 站点,消息文本是 URL 的一部分。为了避免 URL 中的空格,我调用 HttpUtility.Encode() 对其进行 URL 编码。

But I keep getting an URIFormatException - "Invalid URI: The format of the URI could not be determined" - when I use code similar to this:

但是我不断收到 URIFormatException -“无效的 URI:无法确定 URI 的格式” - 当我使用类似于以下的代码时:

string url = "http://www.stackoverflow.com?question=a sentence with spaces";
string encoded = HttpUtility.UrlEncode(url);

WebRequest r = WebRequest.Create(encoded);
r.Method = "POST";
r.ContentLength = encoded.Length;
WebResponse response = r.GetResponse();

The exception occurs when I call WebRequest.Create().

当我调用 WebRequest.Create() 时发生异常。

What am I doing wrong?

我究竟做错了什么?

采纳答案by Mario Menger

You should only encode the argument, not the entire url, so try:

您应该只对参数进行编码,而不是对整个 url 进行编码,因此请尝试:

string url = "http://www.stackoverflow.com?question=" + HttpUtility.UrlEncode("a sentence with spaces");

WebRequest r = WebRequest.Create(url);
r.Method = "POST";
r.ContentLength = encoded.Length;
WebResponse response = r.GetResponse();

Encoding the entire url would mean the :// and the ? get encoded too. The encoded string is then no longer a valid url.

编码整个 url 意味着 :// 和 ? 也得到编码。编码后的字符串不再是有效的 url。

回答by Jason

UrlEncode should only be used on the query string. Try this:

UrlEncode 应仅用于查询字符串。尝试这个:

string query = "a sentence with spaces";
string encoded = "http://www.stackoverflow.com/?question=" + HttpUtility.UrlEncode(query);

The current version of your code is urlencoding the slashes and colon in the URL, which is confusing webrequest.

您的代码的当前版本正在对 URL 中的斜杠和冒号进行 urlencoding,这会混淆 webrequest。