Error 400 when creating InputStreamReader for URL with spaces or accents

2

Hello, I have a problem when I use InputStreamReader to read some URL's that contain spaces or accents. What happens is that I'm reading a URL that contains a JSON (One of the League of Legends APIs). I have no idea what's going on, when I use some Nickname with no accents or spaces I can successfully read JSON, otherwise the URL returns 400 (according to StackTrace) which is "Bad request" for the API. >

Notice that when I use a nick without spaces / accents it works correctly:

Bothimagesabovethecodeworkedcorrectly.

NowwhenIusenickswithspacesandaccents:

I'vealsotriedtoinsertthenickwith"% 20" instead of the blanks, but without success. If I copy the URL as it is in the "read URL" and paste it into the browser I can access JSON perfectly (with "% 20" too).

Code that I'm using for reading:

    URL url = new URL("https://" + server + ".api.pvp.net/api/lol/" + server + "/v1.4/summoner/by-name/" + name + "?api_key=" + key);
    System.out.println("# URL acessada: " + url);

    BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));

    String json = reader.readLine();
    System.out.println("# Lido: " + json);

    JSONObject jsonObject = new JSONObject(json);
    
asked by anonymous 26.03.2016 / 00:15

1 answer

3

I was able to resolve using the following line:

BufferedReader reader = new BufferedReader(new InputStreamReader(((HttpURLConnection) (new URL(url)).openConnection()).getInputStream(), Charset.forName("UTF-8")));

and the URL before ...

"https://" + server + ".api.pvp.net/api/lol/" + server + "/v1.4/summoner/by-name/" + name + "?api_key=" + key

... stayed:

"https://" + server + ".api.pvp.net/api/lol/" + server + "/v1.4/summoner/by-name/" + URLEncoder.encode(name.replaceAll(" ", ""), "UTF-8") + "?api_key=" + key

Sources: Source 1 , Source 2

    
26.03.2016 / 02:47