"使用WebRequest无法确定URI的格式"

Fro*_*rud 11 c# exception httpwebrequest

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

但我不断收到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();
Run Code Online (Sandbox Code Playgroud)

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

我究竟做错了什么?

Mar*_*ger 16

你应该只编码参数,而不是整个网址,所以尝试:

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();
Run Code Online (Sandbox Code Playgroud)

编码整个网址意味着://和?也编码.然后,编码的字符串不再是有效的URL.