我真的很难用 Java 和 PHP 编码字符串。
我使用 Java 来管理 Wordpress 中的帖子。为此,我在 JavaFX 中创建了一个 GUI,并扩展了 REST-API 以创建 SEO 插入。 Worpdress 数据库使用 utf8_general_ci 编码。
我通过 Post 将数据作为 JSON 编码字符串发送到 WP-Api。我使用 org.JSON。用于 Java 中的解码/编码。
我尝试用 php 解码 json 字符串,
json_decode($request->get_param('data'), true);
但我收到以下错误:
Malformed UTF-8 characters, possibly incorrectly encoded
所以我尝试用 php 转换它
$s = iconv("Windows-1252", "UTF-8", $s);
它有效,但像“ä,ö,ü,ß”等字符只是显示为 à, à,...
接下来我尝试用 Java 对其进行编码,如此处所述 Converting Java String From/to utf-8
private String convertToUTF8(String s) {
String out = null;
try {
out = new String(s.getBytes("UTF-8"), "ISO-8859-1");
} catch (java.io.UnsupportedEncodingException e) {
return null;
}
return out;
}
但是有了这个并且没有“iconv”,它再次失败。
我做错了什么以及如何解决这个问题?
服务器运行php7.0。我使用 jdk1.8.0_66 for Java。
最佳答案
使用String
对象分配加密是一个常见的错误。 String
应该是对编码等实现细节的抽象。只要您只使用 String
,您只需知道它们是 Unicode 即可。仅当您将 String
转换为字节时,特定编码才会起作用,在您的情况下,这可能意味着在某些 HTTP 客户端中。我不知道你用什么,所以我附上了 Apache 的一个示例。
public void sendMessage(CloseableHttpClient client, String endpointUrl, String jsonString) throws IOException {
HttpPost post = new HttpPost(endpointUrl);
post.addHeader("Content-Type", "application/json; charset=utf-8"); // Apache would probably set it for you, but since I'm not 100% sure, I added it here.
post.setEntity(new StringEntity(jsonString, ContentType.create("application/json", Consts.UTF_8))); // here the actual conversion takes place and only here do you need to worry about encoding
try (CloseableHttpResponse response = client.execute(post)) {
// act on response here
}
}
备注1:这个例子只是一个例子,旨在说明一点。我没有测试过,而且我不太了解 Apache HTTP 客户端,所以要小心。
备注2:似乎可以使用ContentType APPLICATION_JSON
代替ContentType.create("application/json", Consts.UTF_8)
- 默认情况下使用 UTF-8。但在你的问题的背景下,这种方式似乎更清楚。
关于java - 使用java编码的json字符串无法使用php解码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41917174/