我有一个Android应用程序将文本写入外部数据库。让我们一起玩文字:frodå
简而言之,这是我将代码转发到服务器的方式:
params.add(new BasicNameValuePair("user_name", name_et.getText().toString()));
JSONParser jsonParser; jsonParser = new JSONParser();
JSONObject json = jsonParser.makeHttpRequest(insert_username, "POST", params);
然而问题是,PHP脚本正确接收文本(我通过邮件发送给自己并收到frodå文本),但只有 frod 是写入数据库。
当我使用$user_name = 'frodå';
而不是$user_name = $_POST['user_name'];
在浏览器中输入脚本来手动运行脚本时,文本会正确写入数据库。这怎么可能?
这是php脚本:
<?php
header('Content-type: text/html; charset=UTF-8');
ini_set('default_charset', 'utf-8');
require_once($_SERVER['SERVER_ROOT'].'dbauth.php');
include("PHPMailer/class.phpmailer.php");
$response = array();
try {
$conn = new PDO("mysql:host=$host;dbname=$database", $username, $password, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
$response = '0';
}
$userID = $_POST['userID'];
$user_name = $_POST['user_name'];
try {
$stmt = $conn->prepare("UPDATE APPUSERS SET USERNAME=? WHERE USERID=?");
$stmt->execute(array($user_name, $userID));
$response["success"] = 1;
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
$response["success"] = 0;
}
//Then here I use PHPMailer to send the text received by POST to myself to check
that the POST variable is the correct variable. I receive frodå by mail which means
the correct text is received, but only frod is written into database. I tried this
out many times.
我还可以在数据库中手动添加突出显示的字符。该表编码为utf8_general_ci。
我认为问题在于我在Android中使用JSON转发的文本不是UTF8编码的。你怎么看?我该怎么办呢?
答案 0 :(得分:0)
我认为你发现了上次陈述的问题;您没有向您的PHP脚本发送UTF8数据。以下是我的工作方式。
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("www.myurl.com");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
// handle exception
}
然后,在阅读回复时。
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"), 8);
sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
String line = "0";
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
sb.deleteCharAt(sb.length() - 1);
is.close();
result = sb.toString();
} catch (Exception e) {
// handle exception
}