【问题标题】:Sending utf8 string using json from android to php使用json从android发送utf8字符串到php
【发布时间】:2018-01-27 09:35:40
【问题描述】:

我正在使用以下方法将数据从 android 应用程序发送到 php 脚本:

    JSONObject jsonObject= new JSONObject();
    try {
        jsonObject.put("name", "name ąęś");
        jsonObject.put("address", "address żżóóó");
        jsonObject.put("title", "title ćććżżżóóó");

    } catch (JSONException e) {
        e.printStackTrace();
    }zamiast



    JSONParser jsonParser = new JSONParser();
    String url = "http://www.serwer.com/script.php";

    // Building Parameters
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("post", jsonObject.toString()));
    // getting JSON Object
    // Note that create product url accepts POST method
    JSONObject json = jsonParser.makeHttpRequest(url, "POST", params);

在 php 脚本站点中,我收到这样的数据:

if(isset($_POST['post']))
{
    $post_utf8 = htmlentities($_POST['post'],ENT_QUOTES, "UTF-8");
    $postX = htmlspecialchars_decode($post_utf8);

    $post_x = json_decode($postX, true);

    echo $_POST['post']; //--> problem with utf8 , "?" instead polish characters
    echo $post_x['name']; //--> problem with utf8 , "?" instead polish characters
    echo "ąęź"; // --> everything OK, I can see polish characters
}

我总能看到“?”而不是波兰语字符。 使用 echo "ąźć" 我可以看到波兰语字符。 这就是 POST 方法的问题。 我已经检查了很多东西,但不幸的是我直到现在都没有找到解决方案。

【问题讨论】:

    标签: php android json


    【解决方案1】:

    当使用 UTF-8 向 PHP 服务器应用程序发出 AJAX 请求时,您必须确保 1) 前端支持 UTF8(提交表单时,例如 HTML 编码必须设置为 UTF8),2) Web 服务器配置为使用UTF-8 (Apache: AddDefaultCharset utf-8), 3) PHP 配置为使用 UTF8。

    【讨论】:

    • 这可能有点困难。我使用网络托管。我无权访问 php / apache 配置文件。这是流行的波兰主机:home.pl。如果他们默认不使用 utf 8,这很奇怪,因为它是波兰主机。
    【解决方案2】:

    Java 字符串使用 Unicode,而 JSON 字符串是 UTF-8 编码的。这就是为什么首先我们需要将 Unicode 字符串更改为 UTF8 字符串,如下所示:

    JSONObject jsonObject= new JSONObject();
    try {
        jsonObject.put("name", "name ąęś");
        jsonObject.put("address", "address żżóóó");
        jsonObject.put("title", "title ćććżżżóóó");
    
    } catch (JSONException e) {
        e.printStackTrace();
    }zamiast
    
    
    
    JSONParser jsonParser = new JSONParser();
    String url = "http://www.serwer.com/script.php";
    
    
    String utf8String = "";
    try {
        utf8String = new String(jsonObject.toString().getBytes("UTF-8"), "ISO-8859-1");
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    
    
    
    
    
    // Building Parameters
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("post", utf8String));
    // getting JSON Object
    // Note that create product url accepts POST method
    JSONObject json = jsonParser.makeHttpRequest(url, "POST", params);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-11-09
      • 2018-10-09
      • 1970-01-01
      • 2012-05-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多