0

I have one problem how I can convert in Java this:

String word="Conformément";

to

this:

String word = "Conform%C3%A9ment";

The second is transformed when the string is passed through web.

Thanks in advance, Mihail

Mihail
  • 5
  • 1

3 Answers3

1

You could do

String encodedWord = URLEncoder.encode(word, "UTF-8");
Reimeus
  • 158,255
  • 15
  • 216
  • 276
0

You may want to use URLEncoder.encode() as suggested in this other thread.

Community
  • 1
  • 1
Lake
  • 4,072
  • 26
  • 36
0

It depends on what part of the URI you wish this word to be inserted in.

Your best bet is to use a library which supports URI Templates. And (shameless plug) I have one which works.

Simply create a template and fill the correct values. I can help you create the template as well.

And no, URLEncoder.encode() does not work for this job. Quoting the README of that project:

There is a very common misconception with this method. It does NOT encode strings for use in URIs, it encodes strings for use in POST data, that is for application/x-www-form-urlencoded data; and in this encoding, spaces become +, not %20!

Here is an example of a template where the word would appear in the query part:

http://my.site/some/where?word={word}

Using the library above, the code would be:

final URITemplate tmpl = new URITemplate("http://my.site/some/where?word={word}");
final VariableMapBuilder builder = VariableMap.newBuilder();
builder.addScalarValue("word", "Conformément");
tmpl.toString(builder.freeze()); // returns the correct result
// Or:
tmpl.toURI(builder.freeze());
tmpl.toURL(builder.freeze());
Community
  • 1
  • 1
fge
  • 119,121
  • 33
  • 254
  • 329