Android 服务器乱码问题通常发生在客户端和服务器之间的字符编码不匹配导致的。以下是解决方案:
---
1. 确保服务器端编码正确
(1) 设置服务器返回的 Content-Type
确保服务器的 HTTP 响应头正确设置字符集,例如:
```http
Content-Type: application/json; charset=UTF-8
```
如果是 Spring Boot 服务器:
```java
produces = "application/json;charset=UTF-8"
```
或者在 `application.properties` 中:
```properties
spring.http.encoding.charset=UTF-8
spring.http.encoding.enabled=true
spring.http.encoding.force=true
```
---
2. 确保 Android 客户端使用 UTF-8 编码
(1) 使用 OkHttp
如果你使用的是 OkHttp,确保请求头包含正确的编码:
```java
Request request = new Request.Builder()
.url("https://yourserver.com/api")
.addHeader("Content-Type", "application/json; charset=UTF-8")
.build();
```
(2) 使用 HttpURLConnection
如果你使用的是 HttpURLConnection,可以这样设置:
```java
HttpURLConnection connection = (HttpURLConnection) new URL("https://yourserver.com/api").openConnection();
connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
connection.setRequestProperty("Accept-Charset", "UTF-8");
```
---
3. 处理 JSON 乱码
如果你解析 JSON 数据时乱码,确保使用 UTF-8 解析:
```java
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
StringBuilder response = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
String jsonResponse = response.toString();
```
---
4. 确保数据库字符集为 UTF-8
如果数据存储在数据库中,确保数据库和表的编码为 UTF-8:
```sql
ALTER DATABASE your_database CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
ALTER TABLE your_table CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
```
---
5. 处理文件乱码
如果服务器返回的是 文件流,确保流的编码方式:
```java
InputStreamReader reader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
BufferedReader br = new BufferedReader(reader);
```
---
总结
1. 服务器端:确保返回的 `Content-Type` 头部正确设置 `charset=UTF-8`。
2. Android 端:设置 `HttpURLConnection` 或 `OkHttp` 请求头,确保 `charset=UTF-8`。
3. JSON 解析:用 `InputStreamReader(inputStream, StandardCharsets.UTF_8)` 读取数据。
4. 数据库编码:设置 `utf8mb4` 以防止乱码问题。
5. 文件流:确保流读取时使用 UTF-8。
这样基本可以解决 Android 客户端和服务器之间的乱码问题!