Error 400 when creating Inputstreamreader for URL with spaces or accents

Asked

Viewed 246 times

2

Hello, I have a problem when I use Inputstreamreader to read some Urls that contain spaces or accents. What happens is that I am 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 without accents or spaces I can successfully read the JSON, otherwise the URL returns 400 (according to Stacktrace) which is "Bad request" for the API.

Note that when I use a nickname without spaces/accents it works correctly: inserir a descrição da imagem aqui

Both above images the code worked properly.

Now when I use nicknames with spaces and accents: inserir a descrição da imagem aqui

I have also tried to insert the nick with "%20" in place of the white spaces, but without success. If I copy the URL as it is in the "read URL" and paste into the browser I can access the JSON perfectly (with "%20" as well).

Code 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);

1 answer

3


I managed to solve using the following line:

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

and in the URL before...

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

...got:

"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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.