使用json从android到服务器发送/恢复阿拉伯语字符(utf8)

时间:2017-04-20 07:27:53

标签: php android json utf-8

我试图将阿拉伯字符存储在服务器上的数据库中。但当我添加一些东西时,它会显示为????????????在数据库中!我试过从我的PHP添加来检查是否来自php文件的问题,但它在数据库中正确添加了文本。所以android和json的错误,如何在android中将json编码为utf8?

这是我的代码:

/// <summary>
/// When RegistrationBuilder is used, there is problem with Generics constraints - in produced ExportDefinition is generics constraint with descriptior CustomType which is not comparable with Type. 
/// * so composition failed on Export not found exception.
/// http://stackoverflow.com/questions/24590096/type-constrained-open-generics-do-not-work-with-registrationbuilder
/// </summary>
public static class PatchCatalogForRegistrationBuilderBug
{
    public static void FixCatalogForRegistrationBuilderBug(this ComposablePartCatalog catalog)
    {
        foreach (var item in catalog)
        {
            object value1;
            if (item.Metadata.TryGetValue("System.ComponentModel.Composition.GenericParameterConstraints", out value1))
            {
                var items = (object[])value1;
                foreach (var entry in items)
                {
                    var types = entry as Type[];
                    if (types != null)
                    {
                        for (int i = 0; i < types.Length; i++)
                        {
                            if (((object)types[i]).GetType().FullName != "System.Reflection.Context.Custom.CustomType") continue; //cast to object is only for due to R# warning
                            types[i] = types[i].UnderlyingSystemType;
                        }
                    }
                }
            }
        }
    }
}

用于添加的PHP:

    class AddStories extends AsyncTask<String, String, String> {


    protected String doInBackground(String... args) {


        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("Caregiver_ID", ID));
        params.add(new BasicNameValuePair("Title", "قصة"));
        params.add(new BasicNameValuePair("Story", "قصتي بدأت عندما"));

        JSONObject json = jsonParser.makeHttpRequest(url_add_story,"POST", params);

        Log.d("Create Response", json.toString());

        try {
            int success = json.getInt(TAG_SUCCESS);

            if (success == 1) {
                suc=1;

                sucess();


            }
            else {
                suc=0;
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return null;
    }
}

当我尝试从android中检索时,我得到了以下内容:

  <?php
  header("Content-Type: text/html; charset=utf-8");


 // array for JSON response
 $response = array();

 // check for required fields
 if (isset($_POST['Caregiver_ID'])  && isset($_POST['Title'])&& isset($_POST['Story'])) {

$Caregiver_ID = $_POST['Caregiver_ID'];
$Title = $_POST['Title'];
$Story = $_POST['Story'];

// include db connect class
require_once __DIR__ . '/db_connect.php';

// connecting to db
$db = new DB_CONNECT();
mysql_query("SET NAMES 'utf8'"); mysql_query('SET CHARACTER SET utf8');

// mysql inserting a new row
$result = mysql_query("INSERT INTO Stories(Caregiver_ID, Title, Story) VALUES('$Caregiver_ID', '$Title','$Story')");

// check if row inserted or not
if ($result) {
    // successfully inserted into database
    $response["success"] = 1;
    $response["message"] = "glossary successfully created.";

    // echoing JSON response
    echo json_encode($response,JSON_UNESCAPED_UNICODE );
} else {
    // failed to insert row
    $response["success"] = 0;
    $response["message"] = "Oops! An error occurred.";

    // echoing JSON response
    echo json_encode($response);
}
} else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";

// echoing JSON response
echo json_encode($response );
}
?>

虽然它在php中正确检索。

PHP代码

  &#1606;&#1577;&#1610;&#1609;&#1572;&#1578;&#1610;&#1604;&#1575;&#1604;&#1575;&#1572;&#1578;&#1610;&#1604;&#1575;&#1575;&#1585;&#1604;&#1575;&#1576;&#1575;&#1585;&#1575;&#1576;&#1610;-&#1575;&#1604;&#1575;&#1604;&#1575;&#1604;&#1578;&#1593;&#1575;

3 个答案:

答案 0 :(得分:0)

在android

中尝试以下代码
ByteArrayOutputStream baos = new ByteArrayOutputStream();

try {
    response = client.execute(httpGet);
    HttpEntity entity = response.getEntity();
    InputStream stream = entity.getContent();
    byte[] buffer = new byte[1024];
    int nread;
    while ((nread = stream.read(buffer)) > 0) {
        baos.write(buffer, 0, nread);             
    }
} catch (ClientProtocolException | IOException e) {
}
//Create a JSON from the String that was return.
JSONObject jsonObject = new JSONObject();
try {
    String jsonText = new String(baos.toByteArray(), StandardCharsets.UTF_8);
    jsonObject = new JSONObject(jsonText);

答案 1 :(得分:0)

您必须在需要添加阿拉伯文字的列之前放置N. 例如N'مختار'。

答案 2 :(得分:0)

根据您的代码,您应该更改此行 $ result = mysql_query(“INSERT INTO Stories(Caregiver_ID,Title,Story)VALUES('$ Caregiver_ID','$ Title','$ Story')”); ........ ..... ... 成为 $ result = mysql_query(“INSERT INTO Stories(Caregiver_ID,Title,Story)VALUES('$ Caregiver_ID',N'$ Title',N'$ Story')”);