-1

I am making a Json request and I get the data and place it in a list view but some of the strings i get have accents or 'ç' and it doesn't appear correctly. For example, the string is 'Bragança' and i receive 'Bragança' or 'à' and get 'Ã'. If i do the request in the browser, all works properly. My request.

public void makeJsonArrayRequest() {

    RequestQueue queue = AppController.getInstance().getRequestQueue();
    queue.start();
    JsonArrayRequest Req = new JsonArrayRequest(urlJsonObjUtilizadas,
            new Response.Listener<JSONArray>() {
                @Override
                public void onResponse(JSONArray response) {
                    Log.d(TAG, response.toString());
                    // Parsing json

                    for (int i = 0; i < response.length(); i++) {
                        try {
                            JSONObject ementaObj = response.getJSONObject(i);
                            Ementa ementa = new Ementa();


                            ementa.setCantina(ementaObj.getString("cantina"));
                            ementa.setDescricao(ementaObj.getString("descricao"));
                            ementa.setEmenta(ementaObj.getString("ementa"));
                            ementa.setPreco(ementaObj.getInt("preco"));

                            ementaItems.add(ementa);

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                    // notifying list adapter about data changes
                    adapter.notifyDataSetChanged();
                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            VolleyLog.d(TAG, "Error: " + error.getMessage());

        }
    }) {
        //**
        // Passing some request headers
        //*
        @Override
        public Map<String, String> getHeaders()  {
            HashMap<String, String> headers = new HashMap<String, String>();
            headers.put("Content-Type", "application/json; charset=UTF-8");
            return headers;
        }
    };
    // Add the request to the RequestQueue.
    AppController.getInstance().addToRequestQueue(Req);
}

4 Answers4

1

I think this is because of the wrong content type encoding header. You are supposed to use UTF-8 as encoding. Maybe this is working in the browsers because the headers are not case-sensitive (unlike Android). Take a look here for a solution. Essentially they are manually overriding the charset.

Community
  • 1
  • 1
Antrromet
  • 15,294
  • 10
  • 60
  • 75
0

please try to use this code for sending and receiving JSON with utf-8 encoding:

try {
    URL url = new URL("your url");
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();

    conn.setDoOutput(true);

    OutputStreamWriter writer = new OutputStreamWriter(
            conn.getOutputStream(), "UTF-8");
    String request = "your json";
    writer.write(request);
    writer.flush();
    System.out.println("Code:" + conn.getResponseCode());
    System.out.println("mess:" + conn.getResponseMessage());

    String response = "";
    BufferedReader reader = new BufferedReader(new InputStreamReader(
            conn.getInputStream(), "UTF-8"));
    String line;
    while ((line = reader.readLine()) != null) {
        response += line;
    }

    System.out.println(new String(response.getBytes(), "UTF8"));
    writer.close();
    reader.close();
} catch (MalformedURLException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}
meda
  • 45,103
  • 14
  • 92
  • 122
0

You should add the request header charset to UTF-8. For example if your request will be as json, you should add this header to the request:

"Content-type": "Aplicación/json; utf-8"

I use Volley too and this way works for me.

Regards.

Max Pinto
  • 1,463
  • 3
  • 16
  • 29
  • Sorry, i am new in android, how can i add the request header in my code? Thank you. – Tiago Morais Jul 02 '15 at 17:10
  • shure, i will give you real example, check the other answer. – Max Pinto Jul 02 '15 at 19:09
  • I already put the headers in the request but the result is the same. I update my question with the new code. – Tiago Morais Jul 02 '15 at 21:19
  • change this line: headers.put("Content-Type", "application/json; charset=utf-8"); To: headers.put("Content-Type", "application/json; charset=iso-8859-1"); The problem could be the charset, tell me if it works. Regards – Max Pinto Jul 02 '15 at 23:25
0

Check this sample, this way i am using, look the header section

public class Estratek_JSONString extends JsonRequest<String>{
Activity Act;
Priority priority;

public Estratek_JSONString(int m, String url, JSONObject params,
        Listener<String> listener, ErrorListener errorListener,Activity act, Priority p)  {
    super(m,url,params.toString(),listener,errorListener); 

    this.Act=act;
    this.priority=p;    
} 
public Estratek_JSONString(int m, String url,
        Listener<String> listener, ErrorListener errorListener,Activity act, Priority p)  {
    // super constructor

    //super(m,url,params.toString(),listener,errorListener);
    super(m,url,null,listener,errorListener);

    this.Act=act;
    this.priority=p;    
} 

@Override
public Map<String, String> getHeaders()  {
        HashMap<String, String> headers = new HashMap<String, String>();
        headers.put("Content-Type", "application/json; charset=utf-8");
        headers.put("Authorization", "Bearer "+Tools.Get_string(Act.getApplicationContext(),Global_vars.Access_token));
        return headers;
    }

//it make posible send parameters into the body.
  @Override
  public Priority getPriority(){
    return priority;
 }

  @Override
    protected Response<String> parseNetworkResponse(NetworkResponse response) {
        try {
            String jsonString =
                new String(response.data, HttpHeaderParser.parseCharset(response.headers));
            return Response.success(new String(jsonString),
                    HttpHeaderParser.parseCacheHeaders(response));
        } catch (UnsupportedEncodingException e) { 
            return Response.error(new ParseError(e));
        }
    }

}

Max Pinto
  • 1,463
  • 3
  • 16
  • 29