3

I tried using Ruby's url_encode (doc here.)

It encodes http://www.google.com as http%3A%2F%2Fwww.google.com. But it turns out that I cannot open the latter via a browser. If so, what's the use of this function? What is it useful for, when the URL that it encodes can't even be opened?

2 Answers 2

2

A typical use is the HTTP GET method, in where you need a query String.

Query String 1:

valudA=john&valueB=john2

Actual value server get:

  • valueA : "john"

  • valueB : "john2"

url_encode is used to make the key-value pair enable to store the string which includes some non-ASCII encoded character such as space and special character.

Suppose the valueB will store my name, code 4 j, you need to encode it because there are some spaces.

url_encode("code 4 j")
code%204%20j

Query string 2:

valueA=john&valueB=code%204%20j

Actual value server get:

  • valueA: "john"
  • valueB: "code 4 j"
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for your answer! So, why can't the server store it as code 4 j with spaces? What's wrong with that?
Thanks for your remind:) I have never thought about this before, What I know from google is that URL is designed to be encoded in ASCII and there is no space in ASCII. I have also updated my answer to non-ASCII encoded character.
2

You can use url_encode to encode for example the keys/values of a GET request.

Here is an example of what a SO search query URL looks after encoding:

https://stackoverflow.com/questions/tagged/c%23+or+.net+or+asp.net

As you can see, url encoding appears to be applied only on the last part of the URL, after the last slash.

In general you cannot use url_encode on your entire URL or you will also encode the special characters in a normal URL like the :// in your example.

You can check a tutorial that explains how it works here: http://www.permadi.com/tutorial/urlEncoding/

Comments

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.