Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 361
Frode Lillerud Avatar asked May 25 '09 14:05

Frode Lillerud


People also ask

What is the format of the URI?

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

What is an invalid URI?

The error message "Invalid URI: The URI is empty" is caused by a mistake in the parameter names typography.


1 Answers

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.

like image 156
Mario Menger Avatar answered Sep 19 '22 09:09

Mario Menger