【发布时间】: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