我面临类似于How to Force a jar to uses(or the jvm running in) utf-8 而不是系统的默认编码的问题。有一个服务器和客户端 java 应用程序。如果我从 Eclipse 运行它们,那么一切正常。如果我制作罐子,那么它们之间交换的字符串就会被破坏(编码错误)。
如果我使用-Dfile.enconding=utf-8
JVM 参数运行两个图像,那么它可以正常工作。但是由于上面的链接说它不是最好的解决方案(至少需要从 bat 运行 jar),我试图通过为 BufferedReader 指定编码来解决这个问题。但是它失败了,并且使用 jar 很难调试。
此代码用于发送请求并获取 JSON 格式的一行作为回复。该回复被证明具有 UTF-8 编码。
public static String sendRequest (String request) {
if (request == null) return null;
try {
URL url = new URL(request);
HttpsURLConnection con = (HttpsURLConnection)url.openConnection();
BufferedReader inReader = new BufferedReader(new InputStreamReader(con.getInputStream(), Charset.forName("UTF-8")));
String line = inReader.readLine();
inReader.close();
return line;
} catch (Exception e) {
e.printStackTrace(System.err);
}
return null;
}
这就是这条线的样子
{"response":[{"uid":123456,"first_name":"Имя","last_name":"Фамилия"}]}
然后我准备在 Gson.fromJson() 中使用它
int beginIndex = reply.indexOf('[');
int endIndex = reply.indexOf(']');
reply = reply.substring(beginIndex + 1, endIndex);
SocialPerson vkPerson = new Gson().fromJson(reply, SocialPerson.class);
之后,使用由 ChannelBuffers.wrappedBuffer() 和 NettyUtils.writeStrings() 生成的 Netty 的 ChannelBuffer 将字符串发送到服务器
我尝试在 Eclipse 中调试客户端和从 jar 运行的服务器,然后 Eclipse 显示,直到字符串真正提供给框架以交付它看起来有效。
然后我从 Jar 调试服务器和客户端运行,一旦收到字符串,它看起来已经像垃圾了。
在服务器端
private final String username;
private final String password;
public SimpleCredentials(ChannelBuffer buffer)
{
this.username = NettyUtils.readString(buffer);
this.password = NettyUtils.readString(buffer);
}
你认为问题可能出在哪里?对不起,我不能在这里发布所有代码。
UPD: 用户名由 firstName 和 lastName 生成
ChannelBuffer buffer = ChannelBuffers.wrappedBuffer(opCode, NettyUtils.writeStrings(userId, userName, refKey));