我将一些数据从 Java 发布到 PHP:
try {
URL obj = new URL("http://myphpurl/insert.php");
HttpURLConnection conn = (HttpURLConnection) obj.openConnection();
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.setRequestMethod(POST_METHOD);
conn.setDoInput(true);
conn.setDoOutput(true);
Map<String, String> params = new HashMap<String, String>();
params.put("title", "العربية");
OutputStream os = conn.getOutputStream();
BufferedWriter writer =
new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(getQuery(params));
writer.flush();
writer.close();
os.close();
BufferedReader in =
new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
String inputLine;
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
LOG.debug("response {}", response);
in.close();
response = null;
inputLine = null;
conn.disconnect();
conn = null;
obj = null;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
private String getQuery(Map<String, String> params) throws UnsupportedEncodingException {
StringBuilder result = new StringBuilder();
boolean first = true;
Iterator<Map.Entry<String, String>> it = params.entrySet().iterator();
while (it.hasNext()) {
if (first)
first = false;
else
result.append("&");
Map.Entry<String, String> pairs = it.next();
result.append(URLEncoder.encode(pairs.getKey(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(pairs.getValue(), "UTF-8"));
it.remove(); // avoids a ConcurrentModificationException
}
return result.toString();
}
insert.php 文件如下所示:
<?php
$posttitle = $_POST["title"];
echo "$posttitle";
echo urldecode($posttitle);
?>
回显显示一些乱码مليون
,而不是实际的标题?????????
。
然后这个乱码会被插入到 mysql 数据库中。
其他信息:
数据库是
utf8_general_ci
并且支持阿拉伯语(当我使用 phpMyAdmin 手动更新帖子时,它可以工作)。我在
InputStreamReader
和InputStreamWriter
中添加了UTF-8
,并且出现以下行为:- Windows 上的 Tomcat6,CentOS 上的(PHP + mysql)--> 好的
- CentOS 上的 Tomcat6、CentOS 上的(PHP + mysql)--> 不行
其他信息 2
- 使用 JavaScript 进行发布工作正常:页面使用正确的编码进行响应。
最佳答案
您的代码可能会出现很多问题,但我们无法对其进行测试。另外,我建议使用功能齐全的 HTTP 客户端而不是 URLConnection
。您应该检查的内容列表:
- 将正确的源文件编码传递给
javac
(您的测试是硬编码的。您是否运行相同的二进制文件,或者从 IDE 运行该程序,还是在部署计算机上重新编译?)< - 使用 UTF-8 对查询字符串进行编码
- 如果您的 API 使用 HTTP 请求正文,请检查两端是否同意编码,和/或使用 Content-Type MIME header
- PHP 具有二进制字符串(必须给出编码),因此请确保在连接到数据库和/或进行相应转码时使用适当的参数
- 从 PHP 服务器发送文本时,请注意模板和动态位的编码!
Activity 部件的数量相当大。您不应该通过 print/echo 进行调试,因为这会增加另一个级别的转码。如果可能,转储原始文本字节并使用十六进制编辑器。
有趣的是 Windows → Linux 可以,而 Linux → Linux 不行。您可能想要检查两台 CentOS 计算机上的区域设置(可能从目标进程内部运行操作系统命令 - JVM 和 Apache)
关于java - 将非拉丁数据从 Java 发送到 PHP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26675140/