Java – About special characters in Java

About special characters in Java… here is a solution to the problem.

About special characters in Java

In my application about World of Warcraft mythical dungeons, I had to make some queries against the raiderio public API. I had a big problem when players named it that way:

https://raider.io/api/v1/characters/profile?region=US&realm=https://raider.io/characters/us/zuljin/Børomìr&name=&fields=mythic_plus_best_runs% 3Aall

this name : Børomìr

In the API, this query doesn’t work because it manages special characters like :

https://raider.io/api/v1/characters/profile?region=us&realm=zuljin&name=B%C3%B8rom%C3%ACr&fields=mythic_plus_best_runs%3Aall

becomes this : B%C3%B8rom%C3%ACr

Where:

o becomes %C3%B8

ì becomes %C3%AC

What tools do I need to generate this transformation in Java?

This is the URL request code:

            String body = "";
            URL url = new URL("https://raider.io/api/v1/characters/profile?region="+region.toString()+"&realm="+realm+"&name="+name+"&fields=mythic_plus_best_runs%3Aall");
            System.out.println(url.toString());
            URLConnection uc = url.openConnection();
            uc.addRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)");
            InputStream in = uc.getInputStream();
            String encoding = uc.getContentEncoding();
            encoding = encoding == null ? "UTF-8"
                     "windows-1251"
                     "Cp1251"
                    : encoding;
            body = IOUtils.toString(in, encoding);

Solution

You will use Java’s URLEncoder like URLEncoder.encode("Børomìr", "UTF-8");

Related Problems and Solutions