【问题标题】:Wrong character encoding in POST requestPOST 请求中的字符编码错误
【发布时间】:2013-09-18 20:52:51
【问题描述】:

我需要在 MySQL 数据库中存储字符串“Wiadmość”,但更新的记录具有值“Wiadomość”。这是我的 POST 方法

private static String post(String endpoint, List<NameValuePair> params) throws IOException
{
  HttpParams httpParameters = new BasicHttpParams();
  HttpProtocolParams.setContentCharset(httpParameters, HTTP.UTF_8);
  HttpProtocolParams.setHttpElementCharset(httpParameters, HTTP.UTF_8);

  HttpClient httpclient = new DefaultHttpClient(httpParameters);

  HttpPost httppost = new HttpPost(endpoint);
  String responseBody="NULL RESPONSE";

      httppost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
      ResponseHandler<String> responseHandler=new BasicResponseHandler();
      responseBody = httpclient.execute(httppost, responseHandler);
return responseBody;
}

我的 PHP 脚本:

<?php

if (isset($_POST["did"]) && isset($_POST["dpw"]) && isset($_POST["msg"])) {
$did = $_POST["did"];
$dpw = $_POST["dpw"];
$msg = $_POST["msg"];
// Store user details in db
include_once './db_functions.php';

$db = new DB_Functions();

$res = $db->storeMessage($did, $dpw, $msg);

if ($res)
echo "1";
else
echo "0";
echo $msg;
} else {
// user details missing
}
?>

通过 Wireshark,我捕获了来自 php 脚本($msg 值)的回声响应,它看起来是“1Wiadomo\305\233\304\207”。 由 android 设备发送的字符串也被wireshark 捕获,如下所示:“msg=Wiadomo%C5%9B%C4%87”。 从“List NameValuePair params”获得的字符串看起来正确。 数据库编码正确(utf8_general_ci),通过手动记录编辑存储正确数据。

DB_Connect.php

class DB_Connect {

// constructor
function __construct() {

}

// destructor
function __destruct() {
    // $this->close();
}

// Connecting to database
public function connect() {
    require_once 'config.php';
    // connecting to mysql
    $con = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
    mysql_set_charset("utf8",$con);
    // selecting database
    mysql_select_db(DB_DATABASE);

    // return database handler
    return $con;
}

// Closing database connection
public function close() {
    mysql_close();
}

} 
?>

【问题讨论】:

  • PHP与MySQL连接的字符集设置是否正确?
  • 您在哪里看到“不正确”的字符串? HTML、PHP、MySQL 视图?确保使用 utf8 输出 html,使用 utf8 提交表单,使用 utf8 连接数据库并将列设置为 utf8 ... 甚至将 php(等)文件保存在 utf8 中。
  • 您是否在head 中设置了meta 标记以表明您的页面是UTF-8?

标签: php android mysql http post


【解决方案1】:

另一种可能的解决方案是设置使用函数http://php.net/manual/en/function.mysql-set-charset.php 来设置mysql 连接上的字符集。或者,您可以事先在 mysql 连接上使用查询 set names utf8;

【讨论】:

  • 请注意,mysql_set_charset() 是特定于 ext/mysql 的(不应该再使用它了)。其他 API 也有其等价物。
【解决方案2】:

utf8_encode() 将您的输入添加到数据库之前。

【讨论】:

  • 这会导致结果字符串看起来像这样 "Wiadomośćść"
  • 听起来您需要更改 mysql 表中的排序规则。
猜你喜欢
  • 2015-05-26
  • 1970-01-01
  • 2023-03-25
  • 2010-10-17
  • 1970-01-01
  • 2016-09-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多