简体   繁体   中英

android and php json utf-8 fail

I have a problem on transmitting utf-8 from android to php. I have looked up many solutions online, but all of them somehow fail sending UTF-8.

My Java code

 String str = "";
    HttpClient httpclient = new DefaultHttpClient();

    HttpPost httppost = new HttpPost(params[0]);
    try {
        // set up post data
        JSONObject json = getJSON();

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

        // Post the data:
        httppost.setHeader("json",json.toString());
        httppost.setEntity(new ByteArrayEntity(json.toString().getBytes("UTF8")));

        httppost.getParams().setParameter("jsonpost",postjson);
        httppost.getParams().setParameter("jsonpost",postjson);
        HttpResponse response = httpclient.execute(httppost);
        if(response != null)
        {
            str = getInputString(response);
            return str;
        }
    }
    catch (UnsupportedEncodingException e) {
        return "";
    }
    catch (Exception e) {
        return "";
    }
    return "";

On the other hand my php

<?php
header'Content-Type:text/plain; charset=utf-8');

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

echo $message;
?>

The output I receive is just a blank string if it is a chinese character like, "欢迎", but if it is like 'Welcome'. The message would have an output Welcome. What is the main problem here? IT would be thankful if someone helped. Thanks.

Solution:

$data = json_decode(file_get_contents('php://input'));
$message = $data->message;

echo $message;
?>

why do you use a BiteArray ? you could simply do that like that:

httpPost.setEntity(new UrlEncodedFormEntity(values, HTTP.UTF_8)

where values ( List<NameValuePair> ) will be the param.

Set the utf-8 on your ini also use this function on php script:

ini_set('default_charset', 'utf-8');

put this code on:

<?php
 ini_set('default_charset', 'utf-8');
$json = $_SERVER['HTTP_JSON'];
$data = json_decode($json);
$message = $data->message;

echo $message;
?>

Even if this question is dated 2012, it seems the problem is not solved and same kind of question stay unsolved.

As I'm working on APP using a huge amount of data transfert between tablets and PHP Web servers, using French and Portuges languages, so with "stange char", I've made some tests:

  • When you send data with your Android Tablet to PHP Web site you just have to prepare your data using such a way:

     List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); nameValuePairs.add(new BasicNameValuePair("op","_CID1")); nameValuePairs.add(new BasicNameValuePair("la",la)); nameValuePairs.add(new BasicNameValuePair("lo",lo)); nameValuePairs.add(new BasicNameValuePair("id",codigo)); // Encoding URL for GET String the_param = URLEncodedUtils.format(nameValuePairs,"utf-8"); String url = the_url + "?" + the_param; 

On PHP side, you have to test the existence of values using isset (so in this case isset($_GET['op']); and so on, then, you have to perform a validation of data using SQL, in order to prevent SQL injection and decode de values. For that, just use :

$result = @mysqli_real_escape_string ($handle,$var);

where hanlde is the handle you get after opening the DB and $var is the value you get from Android. (example is using SQLi)

  • When you get data from PHP, meaning your PHP web site "echo" data and the tablet get them. Two options:

Simple one is perform, in PHP side, a utf8_decode (I write DECODE not encode!!) So, if you do, on PHP side:

$str = "Não, l'été c'est pour bientôt";
echo $str;

You'll get wrong string under Android. To get perfect values you must do:

    $str = "Não, l'été c'est pour bientôt";
    $str = utf8_decode($str);
    echo $str;

To get the string on Android, just do:

            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(url[0]);
            HttpResponse resp = httpclient.execute(httppost);
            HttpEntity ent = resp.getEntity();
            text = EntityUtils.toString(ent);

Explanation: basicly, on PHP side, the string is UTF8. When you perform the utf8-decode you set the string to ISO-8859-1 which the defaut value on Android (see EntityUtils doc).

If you don't do the utf8_decode on PHP side, you will transmit the data using utf8 which is unknow by defaut on Android. In that case, you will have to perform an EntityUtils with parameter utf8.

In fact, or you transforme UTF8 to ISO-8859-1 on PHP side and then transmit and use ISO-8859-1 (option 1) or you transmit UTF8 and so, need to transform on Android side using EntityUtils (option 2).

Hope this will help Peter

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