【问题标题】:Android: Sent UTF-8 data to MySQLAndroid:将 UTF-8 数据发送到 MySQL
【发布时间】:2015-07-13 16:48:12
【问题描述】:

我使用 php 和 json 将数据保存到 mysql db,但我的数据转换为 ?,我在 php 和 db connect 和 java 代码中使用 utf-8

php

<?php
header("Content-type: application/json; charset=utf-8");
mb_internal_encoding('UTF-8');
mb_http_output('UTF-8');

$hostname='localhost';
$username='ekht3r44_6785h5h';
$password='IFVB!8Nw{#-S';
$response = array();

.
.
.
$dbh=new PDO("mysql:host=$hostname;dbname=db;charset=utf8mb4",$username,$password);

$sql="INSERT INTO contact_form (name,email,subject,message) VALUES (".$_POST['name'].",".$_POST['email'].",".$_POST['subject'].",".$_POST['message'].");";

$statement = $dbh->prepare("INSERT INTO contact_form (name,email,subject,message) VALUES (:name,:email,:subject,:message);");
$statement->execute(array(':name' => $_POST['name'],':email' => $_POST['email'],':subject' => $_POST['subject'],':message' => $_POST['message']));
.
.
.
?>

java

protected String doInBackground(String... args) {
    try {
        // Building Parameters
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("name", et_name.getText().toString()));
        params.add(new BasicNameValuePair("email", et_email.getText().toString()));
        params.add(new BasicNameValuePair("subject", et_subj.getText().toString()));
        params.add(new BasicNameValuePair("message", et_msg.getText().toString()));
        // defaultHttpClient
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);

        httpPost.setEntity(new UrlEncodedFormEntity(params,"UTF-8"));

        HttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();
        is = httpEntity.getContent();
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    try {

        BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"), 8);
        StringBuilder sb = new StringBuilder();

        String line = null;
        while ((line = reader.readLine()) != null)
        {
            sb.append(line + "\n");
        }
        is.close();
        page_output = sb.toString();
    } catch (Exception e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }

    return page_output;
}

你能检查一下哪里出错了。

【问题讨论】:

    标签: java php mysql utf-8


    【解决方案1】:

    请检查您在 MySQL 中的表的字符集。那个“可能”就是原因。

    【讨论】:

    • tnx,用ALTER TABLE contact_form CONVERT TO CHARACTER SET utf8;解决
    猜你喜欢
    • 2016-03-26
    • 2016-08-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-22
    • 2014-01-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多