简体   繁体   中英

Send special characters in JSON from android to PHP

I want to send a JSON to a PHP file that I have on my server, it works fine except when some field contains a special characters (accents, ñ, etc.).

Java file:

    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(uri);

    JSONObject json = new JSONObject();

    try {
        // JSON data:
        json.put("id_u", viaje.getID_U());
        json.put("id_vo", viaje.getID_VO());
        json.put("titulo", viaje.getTitulo());
        [...]

        JSONArray postjson=new JSONArray();
        postjson.put(json);

        // Post the data:
        httppost.setHeader("json",json.toString());
        httppost.getParams().setParameter("jsonpost",postjson);

        // Execute HTTP Post Request
        System.out.print(json);
        HttpResponse response = httpclient.execute(httppost);

PHP file:

$json = $_SERVER['HTTP_JSON'];
$data = json_decode($json);

$id_u = $data->id_u;
$id_vo = $data->id_vo;
$titulo = $data->titulo;
[...]

For example, if titulo = "día", $title is empty, but instead whether titulo = "example" works correctly. I do not know how to convert to utf-8 before sending the items, I tried many things and nothing works for me. Any idea?


EDIT:

I could solve the problem. It was clear that the problem was the encoding. I solved by adding 2 lines to the code:

Java file:

// Post the data:
httppost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
httppost.setHeader("json",json.toString());
httppost.getParams().setParameter("jsonpost",postjson);

PHP file:

$json = $_SERVER['HTTP_JSON'];
$cadena = utf8_encode($json);
$data = json_decode($cadena);

thanks for your help! :)

Sounds like an encoding issue. Try setting the encoding like this:

HttpPost httppost = new HttpPost(builder.getUrl());
httppost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");

You can also force the proper encoding on your content like this. But that's probably not needed here:

// Add your data
httppost.setEntity(new UrlEncodedFormEntity(builder
     .getNameValuePairs(), "UTF-8"));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM