4

I know that should be basics but i had no formation :( and I don't understand it, everywhere it seems obvious to people. I get that one side encode data with his set and android is probably expecting another one, but what can I do to translate?

My app perform a get request on google maps api to retrieve an address from a Lat/lng. But I failed to decode properly the result as a French è is displayed as è

I have not enough xp in Java to understand what to do. It is linked with UTF-8, right?

What should I do?

            response = client.execute(httpGet);
            HttpEntity entity = response.getEntity();
            InputStream stream = entity.getContent();
            int b;
            while ((b = stream.read()) != -1) {
                stringBuilder.append((char) b);
            }
            JSONObject jsonObject = new JSONObject();
            jsonObject = new JSONObject(stringBuilder.toString());
            retList = new ArrayList<Address>();
            if("OK".equalsIgnoreCase(jsonObject.getString("status"))){
                JSONArray results = jsonObject.getJSONArray("results");
                for (int i=0;i<results.length();i++ ) {
                    JSONObject result = results.getJSONObject(i);
                    String indiStr = result.getString("formatted_address");
                    Address addr = new Address(Locale.ITALY);
                    addr.setAddressLine(0, indiStr);
                    Dbg.d(TAG, "adresse :"+addr.toString());
                    retList.add(addr);
                }
            }

Thanks for help !

Poutrathor
  • 1,990
  • 2
  • 20
  • 44

2 Answers2

10

Try using UTF-8,

instead of using InputStream try something like,

String responseBody = EntityUtils.toString(response.getEntity(), HTTP.UTF_8);
Lalit Poptani
  • 67,150
  • 23
  • 161
  • 242
  • 1
    it works ! thanks When u specify UTF_8 you are saying that the first param is in UTF-8 ot that u want a UTF-8 encoded result? – Poutrathor Sep 25 '13 at 15:09
  • 1
    There are always like 50 ways to get to the goal and the simplest one is the last one you find. Most examples use Stream reading constructs, this one is way nicer to use and likely as efficient if you just want it in a String. – John Dec 01 '14 at 00:06
  • It is simple but you will end up with OutofMemoryError if you don't use a buffer and the entity is too large. http://stackoverflow.com/questions/7795591/android-httpentityutils-outofmemoryexception – Kerem Dec 25 '14 at 01:20
  • @mass its obvious that you neeed to change the things when you require :) – Lalit Poptani Dec 25 '14 at 05:09
0

you can use BufferReader
your code will be like this:

InputStream stream = entity.getContent();
BufferedReader br = new BufferedReader(new InputStreamReader(stream, "UTF-8"));
        int b;
        while ((b = br.read()) != -1) {
            stringBuilder.append(b);
        }
Saif Hamed
  • 1,084
  • 1
  • 12
  • 17