Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to force %20 instead of + in System.Net.WebUtility.UrlEncode

Tags:

I need to encode a URL in a class library assembly where I don't want to reference System.Web. The URL contains several spaces

https://query.yahooapis.com/v1/public/yql?q=select * from yahoo.finance.quote where  symbol in ("YHOO","AAPL")&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback= 

When I use System.Net.WebUtility.UrlEncode() the spaces are replaced with "+" which doesn't work. I need them to be replaced with %20

How can I achieve this without referencing System.Web?

like image 760
ChrisP Avatar asked Sep 09 '15 16:09

ChrisP


People also ask

How do you change the special characters in a URL?

URL encoding replaces unsafe ASCII characters with a "%" followed by two hexadecimal digits. URLs cannot contain spaces. URL encoding normally replaces a space with a plus (+) sign or with %20.

Do I need to URLEncode?

Why do we need to encode? URLs can only have certain characters from the standard 128 character ASCII set. Reserved characters that do not belong to this set must be encoded. This means that we need to encode these characters when passing into a URL.

What does Httputility URLEncode do?

Converts a string that has been HTML-encoded for HTTP transmission into a decoded string. To encode or decode values outside of a web application, use the WebUtility class.

What is Server URLEncode?

The URLEncode method applies URL encoding rules, including escape characters, to a specified string. URLEncode converts characters as follows: Spaces ( ) are converted to plus signs (+). Non-alphanumeric characters are escaped to their hexadecimal representation.


1 Answers

You could try Uri.EscapeUriString from System assembly, which escapes a URI string. For the string from the question it returns:

https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quote%20where%20%20symbol%20in%20(%22YHOO%22,%22AAPL%22)&format=json&diagnostics=true&env=store%253A%252F%252Fdatatables.org%252Falltableswithkeys&callback= 
like image 126
Oleks Avatar answered Sep 22 '22 12:09

Oleks