我找不到传递给 php 的斯堪的纳维亚字符未正确显示和存储的任何原因。
当我使用 Web 应用程序时,斯堪的纳维亚字符可以与 php 和数据库一起正常工作。
如果我从 web 应用程序将消息写入数据库并将其加载到 Android 应用程序,字符就会正确显示。
在 Android 中
String message = "Tässä"
try {
// open a connection to the site
URL url = new URL("own_url");
HttpURLConnection con = (HttpURLConnection)url.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", "");
con.setRequestProperty("Accept-Language", "fi, en-US,fi;q=0.6, en;q=0.5");
con.setRequestProperty("Accept-Charset", "UTF-8");
// Send post request
con.setDoOutput(true);
String urlParameters = "message=" + message;
在 PHP 中
$message = $_POST['message'];
error_log($message);
error_log 显示为 T\xe4ss\xe4
mysqli_set_charset($con, 'utf8');
date_default_timezone_set('UTC');
$sql = "INSERT INTO messages SET message='$message'";
mysqli_query($con, $sql);
在数据库中是T?ss
编辑
感谢 user2864740 的建议,更改了查询生成以防止 SQL 注入(inject)。
$stmt = $con->prepare("INSERT INTO messages (message) VALUES (?)");
$stmt->bind_param("s", $message);
$stmt->execute();
最佳答案
我找到了问题的解决方案,我需要将 urlParameters 设置为像这样的 byte[]。
String urlParameters = "message=" + message;
byte[] postData = urlParameters.getBytes(StandardCharsets.UTF_8);
DataOutputStream wr = new DataOutputStream( con.getOutputStream()){};
wr.write( postData );
但是API低于19有问题,如下:
StandardCharsets.UTF_8
字段需要 API 级别 19(当前最低级别为 14):java.nio.charset.StandardCharsets#UTF_8
关于java - 当我尝试将带有斯堪的纳维亚字符的字符串从 Android 发布到 Php 时出现什么问题,例如 ÅäÖ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32090663/