【问题标题】:UNICODE TO UTF-8 issue while retrieve from server in android从 android 中的服务器检索 UNICODE TO UTF-8 问题
【发布时间】:2013-02-12 05:12:56
【问题描述】:

我将 unicode 存储在 mysql 数据库中,并尝试在我的 android 应用程序中使用 php 检索它。每当我尝试仅检索 unicode 而不是 utf-8 字符时。我在 http 中将编码指定为 utf-8 并且我在网上搜索了很多解决方案,但仍然没有找到答案。我也用过这个,但还是没有运气。

new String(json_data.getString("message").getBytes(""),"UTF-8")

我在下面发布我的代码。欢迎提出任何建议。我的要求是从服务器获取印地语、乌尔都语或任何语言,我需要显示。所以我做错了什么。 从数据库我得到这个 \u0cb9\u0ccc \u0c85\u0cb0\u0cc6 \u0caf\u0cc1

private class BackgroundTask extends AsyncTask <String, Void, String> {
      @Override
protected String doInBackground(String... url) {
String result = "";
ArrayList<NameValuePair>   nameValuePairs = new ArrayList<NameValuePair>(5);
String prefName = "MyPref";
SharedPreferences prefs=getSharedPreferences(prefName,MODE_PRIVATE);
 nameValuePairs.add(new BasicNameValuePair("username", mname.getText().toString()));
 nameValuePairs.add(new BasicNameValuePair("password", mpassword.getText().toString()));
 nameValuePairs.add(new BasicNameValuePair("regid", regid));
 nameValuePairs.add(new BasicNameValuePair("status_id", "1"));
 nameValuePairs.add(new BasicNameValuePair("clienttype_id", "clienttype_id"));
        try {
      HttpClient httpclient = new DefaultHttpClient();
            Resources resources=getResources(); 
 String urlstr=String.format(resources.getString(R.string.androidexternal));

 HttpPost httppost = new HttpPost(urlstr);// for test db                  
 // Add your data
    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs,"UTF-8"));

              // Execute HTTP Post Request
              HttpResponse  response = httpclient.execute(httppost);

              inputStream = response.getEntity().getContent();

         }catch(Exception e){
             Log.e("log_tag", "Error in http connection "+e.toString());
     }
     //convert response to string
     try{//iso-8859-1,UTF-8
 BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream,"UTF-8"),8000);
             StringBuilder sb = new StringBuilder();
             String line = null;

             while ((line = reader.readLine()) != null) 
                  {
                sb.append(line + "\n");
             }
             inputStream.close();

             result=sb.toString();
     }catch(Exception e){
             Log.e("log_tag", "Error converting result "+e.toString());
     }
      if(result.contains("null")){

      } 
      else
      {
         try{
                    JSONArray jArray = new JSONArray(result);

                    for(int i=0;i<jArray.length();i++)
                    {
                            JSONObject json_data = jArray.getJSONObject(i);

                   if(i>=3){

System.out.println( new String(json_data.getString("message").getBytes(),"UTF-8"));

                         }

                    }
                   startActivity(intent); 

            }
             catch(JSONException e){
                    Log.e("log_tag", "Error parsing data "+e.toString());

            }  catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }  catch (IOException e) {

                e.printStackTrace();
            }

      }
   return result.toString();
  }

服务器端代码是

// select query for login layout if(isset($_REQUEST['username']))
{

    $get_message_sql = mysql_query("SELECT `message`,`language` FROM doctor_custom_message WHERE  `client_id`='".$result['id']."' AND status='1' ");

 $number=mysql_num_rows( $get_message_sql);
   while($e=mysql_fetch_assoc($get_message_sql))
    if($number==0)
    {
        $output[]="null";

    }else{
          $output[]=$e;
          }

//header('content-type: text/plain; charset=utf-8');
    print(json_encode($output));

}// main brace closed

【问题讨论】:

  • 也许这个link会帮助你

标签: php android


【解决方案1】:

尝试删除"UTF-8"表单

httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs,"UTF-8"));

所以应该是httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

因为您已经在使用UrlEncodedFormEntity,所以不需要。

【讨论】:

    【解决方案2】:

    如果你正确设置了json_encode的参数

     $output=json_encode($output,JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP | JSON_UNESCAPED_UNICODE);
    

    编码值和传输数据没有问题,但如果再次不起作用.set

      header('Content-Type: application/json; charset=utf8');
    

    您可以使用 urlencode 对 UTF-8 值进行编码并在 android 上对其进行解码

    喜欢这个

    urlencode('aیgfسبd');
    

    输出

    a%DB%8Cgf%D8%B3%D8%A8d
    

    有了这个输出,你的 json 值没有问题。

    【讨论】:

    • @AnswerMe 不,它是样本,您必须放入 $output。:)
    • 好的,现在看来我很接近了,现在我在浏览器中获得了价值,因为 \u0026(输出太长,这就是为什么我只提供部分答案)让我检查我的日食和我会回复你的
    • mohammad 我已经尝试过,就像你说的那样,但在 android 应用程序中我仍然得到相同的字符串 \u0026 。我的要求是从服务器获取印地语、乌尔都语或任何语言,我需要显示。所以我做错了什么。
    • @AnswerMe 您必须使用 JSONParser 在 android 中解码 Unicode,请参阅此页面以获取示例 androidhive.info/2012/01/android-json-parsing-tutorialstackoverflow.com/questions/3209912/…
    • @AnswerMe 不同之处在于 json 解析器将一些字符串如 \u0026 转换为 unicode 字符串
    猜你喜欢
    • 2010-12-26
    • 1970-01-01
    • 2018-06-17
    • 2011-10-08
    • 2018-04-21
    • 2011-06-11
    • 2014-08-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多