webteckie
webteckie

Reputation: 428

HttpWebRequest does not preserve query string encoding

Sending the following request (notice the encoded id in the query string) but the server gets just "law". Any ideas as to what I'm missing?

string url = "http://localhost/api/cms/content/?id=law&Order@the#house!";

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "GET";

using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
    ...
}

Upvotes: 0

Views: 1198

Answers (4)

user2864740
user2864740

Reputation: 61975

The problem is & is not a "query string encoding" - it is an XML/HTML entity-escape and the server (correctly) breaks the id parameter at the & in the query string. The server cares about URLs, not XML.

See Percent Encoding (aka URI encoding) for how to correctly1 write the URL which is

..content/?id=law%26Order%40the%23house%21

1 The actual rules are a bit more complex (ie. the @, !, and ; did not need to be encoded) - as "reserved characters that have no reserved purpose in a particular context may also be percent-encoded but are not semantically different from those that are not".

For details, see What every web developer must know about URL encoding which provides a good review and some guidelines on how to correctly construct URLs.

Upvotes: 2

Tomer Klein
Tomer Klein

Reputation: 446

The problem is & is not a "query string encoding" - it is an XML/HTML entity-escape Use it like this:

string url = "http://localhost/api/cms/content/?id=law&Order@the#house!";

works for me

Upvotes: 0

Mahmod Omar
Mahmod Omar

Reputation: 11

Please be sure to encode your characters in the url

for example ('&')is "%26"

this is called reserved characters Like : ! # $ ' ( ) * + , / : ; = ? @ [ ]

check this url plz

http://www.w3schools.com/tags/ref_urlencode.asp

Upvotes: 1

mybirthname
mybirthname

Reputation: 18127

!   #   $   &   '   (   )   *   +   ,   /   :   ;   =   ?   @   [   ]
%21 %23 %24 %26 %27 %28 %29 %2A %2B %2C %2F %3A %3B %3D %3F %40 %5B %5D

Here how you should encode it the query string.

Here for your case:

http://localhost/api/cms/content/?id=law%26Order%40the%23house%21

Upvotes: 1

Related Questions