2

So heres my problem. I'm reading a json from web using httpurlconnection. That json contains german special chars (äöü). Inside NetBeans, everything is fine. When I build the jar an run it, "Silberanhänger" changes to "Silberanhänger". Heres the code, nothing special inside

URL url = new URL("jsonUrl);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setUseCaches(false);
con.setRequestProperty("Accept-Language","de-de,de;q=0.8,en-us;q=0.5,en;q=0.3"); 
con.setRequestProperty("Cookie","s="+session);
try (BufferedReader bf = new BufferedReader(new InputStreamReader(
                     con.getInputStream()))) {
            jsonRepresentation = bf.readLine(); //only 1 line
}
con.disconnect();
System.out.println(jsonRepresentation) // "ä" in IDE, "ä" in Live
Marko
  • 20,385
  • 13
  • 48
  • 64
  • have you tried setting the jvm encoding -Dfile.encoding=UTF8 ? – dngfng Sep 26 '12 at 12:51
  • thank you for this. running the jar with that parameter immediately solved the issue. however, can we get this into the code? it looks like {code}System.setProperty("file.encoding", "UTF8");{/code} doesnt have any influence. – user1696680 Sep 26 '12 at 12:56
  • 1
    You can't do it at runtime, you can find a detailed answer as to why this is the case here: http://stackoverflow.com/questions/361975/setting-the-default-java-character-encoding – dngfng Sep 26 '12 at 12:59
  • red the whole thing + oracle bugreport. what i yet not understand is why my jvm doesnt use 8tf8 at all, since i yet told my netbeans project to do so in the project properties. – user1696680 Sep 26 '12 at 13:20
  • The netbean project properties are only used by netbeans, they don't have anything todo with the compiled and deployed project. When a JVM starts up it uses the standard system encoding by default, unless you override it by setting enviorment variable. – dngfng Sep 26 '12 at 13:22
  • i see. so i have to deal with delivering a .bat/.sh bundle together with my .jar :(. thanks for your help mate :) – user1696680 Sep 26 '12 at 13:34

2 Answers2

0

Set jvm encoding with -Dfile.encoding=UTF8

dngfng
  • 1,923
  • 17
  • 34
0

Setting -Dfile.encoding=UTF8 is a hack that will have side-effects on all code run on that JVM. A better hack would be to specify the charset in the InputStreamReader's constructor

new InputStreamReader(con.getInputStream(), "UTF-8")

However this might still fail if the HTTP server on the other end changes its encoding. You would be better off using a HTTP library such as Apache HTTPComponents to parse the HTTP response into a String. It will read the encoding from the HTTP header and do the right thing in all circumstances.

artbristol
  • 32,010
  • 5
  • 70
  • 103