byte[] bytes = json.getBytes("UTF-8");
为您提供 UTF-8 字节序列,因此 URLReader.read 也为您提供 UTF-8 字节序列
但您尝试在不指定编码器的情况下进行解码,即new String(URLReader.read("pl", "en", "koń"))
所以Java将使用你的系统默认编码来解码(不是UTF-8)
Try :
new String(URLReader.read("pl", "en", "koń"), "UTF-8")
Update
这是我的机器上完整工作的代码:
public class URLReader {
public static byte[] read(String from, String to, String string) {
try {
String text = "http://translate.google.com/translate_a/t?"
+ "client=o&text=" + URLEncoder.encode(string, "UTF-8")
+ "&hl=en&sl=" + from + "&tl=" + to + "";
URL url = new URL(text);
URLConnection conn = url.openConnection();
// Look like faking the request coming from Web browser solve 403 error
conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-GB; rv:1.9.2.13) Gecko/20101203 Firefox/3.6.13 (.NET CLR 3.5.30729)");
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
String json = in.readLine();
byte[] bytes = json.getBytes("UTF-8");
in.close();
return bytes;
//return text.getBytes();
} catch (Exception e) {
System.out.println(e);
// becarful with returning null. subsequence call will return NullPointException.
return null;
}
}
}
不要忘记将 ń 转义为 \u0144。 Java 编译器可能无法正确编译 Unicode 文本,因此最好用纯 ASCII 编写它。
public class AbcServlet extends HttpServlet {
@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
resp.setContentType("text/plain;charset=UTF-8");
byte[] read = URLReader.read("pl", "en", "ko\u0144");
resp.getOutputStream().write(read) ;
}
}