gpt4 book ai didi

java - Android、PHP 和 UTF-8 问题

转载 作者:行者123 更新时间:2023-12-02 06:43:28 24 4
gpt4 key购买 nike

我正在使用 android 和 PHP 进行一些实验,移动设备是一个客户端,通过 HTTP POST 方法将一些代码发布到 PHP。我正在使用以下代码:

            URL url = new URL(host + webapp + syncURL);

HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Accept-Charset", "UTF-8");
con.setFixedLengthStreamingMode(postParams.getBytes().length);
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");

con.setDoOutput(true);

//send the POST out
PrintWriter out = new PrintWriter(con.getOutputStream());
out.print(postParams);
out.close();

变量postParams采用以下形式:

Parámetros: hora=22%3A15%3A02&precision=25.1520004272461&fecha=2013-09-18&data=%5B%22S%C3%AD%22%5D

原始数据为 hora=22:15:02, precision=25.1520004272461,fecha=2013-09-18data=["Sí"] 存储为Map 对象中的键值。

为了在 postParams 中转换 map ,我使用以下代码:

        StringBuilder parametersAsQueryString = new StringBuilder();
try {
if (parameters != null) {
boolean firstParameter = true;

for (String parameterName : parameters.keySet()) {
if (!firstParameter) {
parametersAsQueryString.append(PARAMETER_DELIMITER);
}

Log.d(LOG_TAG, "Parámetro: " + parameterName + ", value: " + parameters.get(parameterName));

// Agregamos el nombre del parámetro
parametersAsQueryString.append(parameterName).append(PARAMETER_EQUALS_CHAR);

// Agregamos el valor del parámetro
try {
parametersAsQueryString
.append(URLEncoder.encode(parameters.get(parameterName), "UTF-8"));
} catch(NullPointerException npe) {
parametersAsQueryString
.append(URLEncoder.encode("", "UTF-8"));
}

firstParameter = false;
}
}
} catch (UnsupportedEncodingException uee) {
Log.d(LOG_TAG, "Error: " + uee);

但是,数据库中的数据显示为["Sà"]。该数据库是一个 PostgreSQL 数据库,编码为 UTF-8,所以我不认为存在问题。有人可以帮助我吗?提前致谢。

最佳答案

由于Java中的String对象不处理utf-8,因此您需要做的是将数据作为byteArray发送到PHP,您可以使用ByteArrayWriter对象代替

PrintWriter out = new PrintWriter(con.getOutputStream());

你可以使用

ByteArrayWriter = new ByteArrayWriter(con.getOutputStream());

由于您已经在 header 中指定了 utf-8 编码,PHP 应该理解它,只需确保以字节形式发送数据

关于java - Android、PHP 和 UTF-8 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18885844/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com