When Android applications interact with PHP backend databases, Chinese character encoding problems often occur. This article introduces several practical methods to avoid and resolve these encoding issues, ensuring accurate data transmission.
PHP usually encodes data retrieved from the database into UTF-8 format. Therefore, it is important to ensure the database and tables use the utf8 or utf8mb4 charset.
Add the following settings to the MySQL configuration file my.cnf:
[mysqld] character-set-server=utf8 collation-server=utf8_general_ci
After modification, restart the MySQL service. Run the following SQL command to verify charset settings:
SHOW VARIABLES LIKE '%character%';
If the result shows utf8 or utf8mb4, the configuration is successful.
It is recommended to explicitly set the charset to utf8 in PHP after connecting to the database to ensure consistent encoding during data exchange:
<?php $conn = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname); mysqli_set_charset($conn, "utf8"); ?>
When sending HTTP requests from Android, specify UTF-8 encoding to prevent encoding issues during requests and responses.
try { URL url = new URL("http://www.example.com"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Accept-Charset", "utf-8"); InputStream responseInputStream = connection.getInputStream(); } catch (IOException e) { e.printStackTrace(); }
try { DefaultHttpClient httpClient = new DefaultHttpClient(); HttpGet httpGet = new HttpGet("http://www.example.com"); httpGet.setHeader("Accept-Charset", "utf-8"); HttpResponse response = httpClient.execute(httpGet); HttpEntity entity = response.getEntity(); InputStream inputStream = entity.getContent(); } catch (IOException e) { e.printStackTrace(); }
Another common solution is to URL encode Chinese characters to avoid encoding problems during transmission. In Android, use java.net.URLEncoder:
String str = "Chinese characters"; String encodedStr = URLEncoder.encode(str, "UTF-8");
On the PHP side, decode using the urldecode function:
$str = "url%20encoded%20string"; $decodedStr = urldecode($str);
Properly configuring the MySQL database charset, setting charset in PHP connections, and specifying UTF-8 encoding in Android requests can effectively prevent Chinese encoding issues. Additionally, URL encoding is a useful auxiliary approach. Choose the most appropriate method based on your development needs to ensure accurate and stable data transmission.