0

I want to send simple GET request using System.Net.WebRequest. But i have a problem when I try to send on URL-s that contains "Space" character. What i do:

string url = "https://example.com/search?text=some words&page=8";
var webRequest = System.Net.WebRequest.Create(link) as HttpWebRequest;

If i try to use this code, then
webRequest.Address == "https://example.com/search?&text=some words&page=8" (#1)

I can manually add "%20" for UrlEncoded space, but "WebRequest.Create" decodes it, and again i have (#1). How can i do it right?

P.S. sorry for my English.

2 Answers 2

1

Try a plus sign (+) instead of space. Also drop the first ampersand (&); it is only used on non-primary arguments. As in

var url = "https://example.com/search?text=some+words&page=8";
Sign up to request clarification or add additional context in comments.

1 Comment

It's not working. Result:webRequest.Address == "exmple.com/index.php?some+words"
1

You should make parameter values "url-friendly". To achieve that, you must "url-encode" values, using HttpUtility.UrlEncode(). This fixes not only spaces, but many other dangerous "quirks":

string val1 = "some words"; 
string val2 = "a <very bad> value & with specials!";
string url = "https://example.com/search?text=" + HttpUtility.UrlEncode(val1) + "&comment=" + HttpUtility.UrlEncode(val2);

2 Comments

Yes, its(HttpUtility.UrlEncode()) encodes spaces and others, but than "WebRequest.Create(link)" decodes %20 to spaces =) I don't understand its logic...
Don't be confused, it's quite simple, if you know the difference between "internet URL" and "page parameters": internet URLs (consider them like the "full path of the executable" you need to run) don't like spaces, to be replaced by %20 (hex value of blank, %20=32) with the so-called "HttpEncode", while parameters (essentially like program "command line parameters") need to be correctly encoded with "UrlEncode" to map spaces (to "+" sign) and any other "non-standard" characters. That's why you need two types of encoding. If you are clear, I hope you consider my answer as "correct"..:-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.