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?
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.
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.
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.
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.
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=
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