“The format of the URI could not be determined” with WebRequest

前提是你 提交于 2019-12-23 07:12:15

问题


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.

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

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().

What am I doing wrong?


回答1:


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

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.




回答2:


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

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.



来源:https://stackoverflow.com/questions/906932/the-format-of-the-uri-could-not-be-determined-with-webrequest

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!