【问题标题】:java sending UTF-16 data to PHP not workingjava将UTF-16数据发送到PHP不起作用
【发布时间】:2015-12-25 09:45:23
【问题描述】:

我使用 JSON 将数据从 java 发送到 php,使用以下代码:

String url = "abc.php";

JSONObject json = new JSONObject();
json.put("msg", message); // message: "\ud83d\udc4d \ud83d\udc4e"

HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 100000);

HttpPost post = new HttpPost(url);

StringEntity se = new StringEntity("json="+json.toString());
post.addHeader("content-type", "application/x-www-form-urlencoded");
post.setEntity(se);

HttpResponse response;
response = client.execute(post);
String resFromServer = org.apache.http.util.EntityUtils.toString(response.getEntity());

Log.i("resFromServer", resFromServer);

PHP代码是:

if( isset($_POST["json"]) ) {

    $jsonDecode = json_decode($_POST["json"]);

    $msg = $jsonDecode->{"msg"};

    echo $msg;
}

但我得到的输出是 ????

而输出应该是 ???? ????

是否存在一些编码问题?如何解决这个问题?

【问题讨论】:

  • 我认为您需要使用 PHP mb_convert_encoding() 或使用 Java 中的 utf-8 而不是 utf-16 发送。在解码 json 之前转换它。
  • @frz3993 你能告诉我怎么做吗?
  • 试试$input = mb_convert_encoding($_POST["json"], "UTF-8", "UTF-16");。然后$jsonDecode = json_decode($input); 继续你的代码。
  • @frz3993 我从 php 收到错误消息,称“尝试获取非对象的属性”。在这种情况下如何获取 $msg?
  • 首先尝试echo mb_detect_encoding($_POST['json']);,以确保您在 PHP 端确实收到了 utf-16。

标签: java php json character-encoding utf-16


【解决方案1】:

试试,先把请求的内容转成utf8 这些字符串实际上可能不是 UTF-16。所以请安全并尝试

if( isset($_POST["json"]) ) {
    $string=$_POST['json'];
    $jsonDecode = mb_convert_encoding($string, "UTF-8", mb_detect_encoding($string));
    $jsonDecode = json_decode($jsonDecode);

    $msg = $jsonDecode->{"msg"};

    echo $msg;
}

【讨论】:

  • @RohitKumar,我认为utf8_encode()是从IS0-8859-1转换为utf-8
  • @RohitKumar 收到错误为“尝试获取非对象的属性”。在这种情况下如何获取 $msg?
  • 似乎对此做更多的研究,java不知道,让我再试一次
  • @RohitKumar var_dump of first $jsonDecode 在使用 mb_convert_encoding($_POST["json"], 'UTF-16', 'UCS-2LE');这非常接近。你能说出 UCS-2LE 以外的其他编码吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-07-18
  • 1970-01-01
  • 2013-04-17
  • 1970-01-01
  • 1970-01-01
  • 2021-01-30
  • 1970-01-01
相关资源
最近更新 更多