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?
The URI comprises: A non-empty scheme component followed by a colon ( : ), consisting of a sequence of characters beginning with a letter and followed by any combination of letters, digits, plus ( + ), period ( . ), or hyphen ( - ).
The error message "Invalid URI: The URI is empty" is caused by a mistake in the parameter names typography.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With