POST请求中的字符编码错误

时间:2013-09-18 20:52:52

标签: php android mysql http post

我需要在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”。 由wireshark捕获的android设备发送的字符串如下所示:“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();
}

} 
?>

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

在将它们添加到数据库之前输入

utf8_encode()