简体   繁体   English

android和php json utf-8失败

[英]android and php json utf-8 fail

I have a problem on transmitting utf-8 from android to php. 我在将utf-8从android传输到php时遇到问题。 I have looked up many solutions online, but all of them somehow fail sending UTF-8. 我在网上查找了许多解决方案,但是所有这些解决方案都无法发送UTF-8。

My Java code 我的Java代码

 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

<?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'. 如果接收到的中文字符是“欢迎”,但如果输入的是“ Welcome”,则我收到的输出只是一个空白字符串。 The message would have an output Welcome. 该消息将具有欢迎输出。 What is the main problem here? 这里的主要问题是什么? IT would be thankful if someone helped. 如果有人帮助,IT部门将非常感激。 Thanks. 谢谢。

Solution: 解:

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

echo $message;
?>

why do you use a BiteArray ? 为什么要使用BiteArray you could simply do that like that: 您可以这样简单地做:

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

where values ( List<NameValuePair> ) will be the param. 其中,值( List<NameValuePair> )将成为参数。

Set the utf-8 on your ini also use this function on php script: 在您的ini上设置utf-8,也可以在php脚本上使用此功能:

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. 即使该问题的日期为2012年,似乎该问题仍未解决,并且同样的问题仍未解决。

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: 由于我正在使用平板电脑和PHP Web服务器之间使用法语和葡萄牙语语言在平板电脑和PHP Web服务器之间传输大量数据的APP进行工作,因此对于“ stange char”,我进行了一些测试:

  • When you send data with your Android Tablet to PHP Web site you just have to prepare your data using such a way: 使用Android Tablet将数据发送到PHP网站时,只需使用以下方式准备数据:

     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 : 在PHP方面,您必须使用isset测试值的存在(因此在本例中为isset($ _ GET ['op']);依此类推,然后必须使用SQL执行数据验证,以便防止SQL注入和解码de值,为此,只需使用:

$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. 其中hanlde是打开数据库后获得的句柄,而$ var是从Android获得的值。 (example is using SQLi) (示例使用SQLi)

  • When you get data from PHP, meaning your PHP web site "echo" data and the tablet get them. 当您从PHP获取数据时,这意味着您的PHP网站“回显”数据,而平板电脑也可以获取它们。 Two options: 两种选择:

Simple one is perform, in PHP side, a utf8_decode (I write DECODE not encode!!) So, if you do, on PHP side: 一个简单的方法是在PHP方面执行utf8_decode(我写的DECODE不编码!!)因此,如果您这样做,则在PHP方面:

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

You'll get wrong string under Android. 在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: 要在Android上获取字符串,只需执行以下操作:

            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. 说明:基本上,在PHP方面,字符串是UTF8。 When you perform the utf8-decode you set the string to ISO-8859-1 which the defaut value on Android (see EntityUtils doc). 执行utf8解码时,请将字符串设置为ISO-8859-1(在Android上为defaut值)(请参阅EntityUtils文档)。

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. 如果您未在PHP端执行utf8_decode,则将使用utf8传输数据,而utaut在Android上是不知道的。 In that case, you will have to perform an EntityUtils with parameter utf8. 在这种情况下,您将必须使用参数utf8执行EntityUtils。

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). 实际上,或者您在PHP方面将UTF8转换为ISO-8859-1,然后传输并使用ISO-8859-1(选项1),或者您传输UTF8,因此需要在Android端使用EntityUtils(选项2)进行转换。

Hope this will help Peter 希望这对彼得有帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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