2015-09-28 68 views
0

我發送數據使用JSON從Java到PHP,使用下面的代碼:的java發送UTF-16數據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; 
} 

但我'得到輸出爲

而輸出應該

有一些編碼的問題?這怎麼解決?

+0

我認爲你需要使用PHP'mb_convert_encoding()'或'發送UTF-8'從Java,而不是'UTF-16'。在解碼json之前轉換它。 – frz3993

+0

@ frz3993請問你能告訴如何? – user5155835

+0

嘗試'$ input = mb_convert_encoding($ _ POST [「json」],「UTF-8」,「UTF-16」);'。然後'$ jsonDecode = json_decode($ input);'繼續執行你的代碼。 – frz3993

回答

0

嘗試先將請求的內容轉換爲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; 
} 
+0

沒有工作,得到相同的錯誤 – user5155835

+0

好吧,嘗試本地化,並很快得出決定性答案.. –

+0

@RohitKumar,我覺得'utf8_encode )'是從IS0-8859-1轉換爲utf-8 – frz3993