5

I need to encode the parameters values in an URL. If I use following:

URLEncoder.encode(url, "UTF-8");

for a URL like this: http://localhost:8080/...

it will encode "://" etc. What I need is the encoding only for the values of the parameters starting from all the URL string. So in this case:

http://localhost/?q=blah&d=blah

I want encoded only the "blah" in the 2 parameters values (for n parameters of course).

What's your best way?

Thanks

Randomize

2 Answers 2

5

You're using URLEncoder in a wrong way. You're supposed to encode every parameter value separately and then assemble the url together.

For example


String url = "http://localhost/?q=" + URLEncoder.encode ("blah", "UTF-8") + "&d=" + URLEncoder.encode ("blah", "UTF-8");

Sign up to request clarification or add additional context in comments.

8 Comments

Yes I know it, the problem is that I got an URL already "done" and I have no way to change the code that generate it
Why then do you need to encode it? Does it contain non ASCII characters?
Then you'll need to build a URL and get the params (or split on the first ? if you're confident of the URL's validity), split them on & (if you don't want that encoded), encode them, then rebuild it.
Indeed if the provided url is valid your only way is to parse it and then encode properly. But it's not an encoding, it's fixing an url.
And of course there'll be problems if some parameter value contained one of characters '?', '&', '='. You may even need to decode parameter values after successful split and then encode them as you need.
|
2

For a URL like http://localhost/hello/sample?param=bla, you could use this (from Java's java.net.URI class):

URI uri = new URI("http", "localhost", "/hello/sample", "param=bla", null);
String url = uri.toASCIIString();

2 Comments

this way you need to preassemble the query string using URLEncoder to encode special characters. And as it turns out Randomize has whole url as input, not its parts.
Well, the URL can be easily broken (split) into such parts and passed along.

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.