我从Servlet中的Perl页面读取HTTP响应,如下所示:
public String getHTML(String urlToRead) {
URL url;
HttpURLConnection conn;
BufferedReader rd;
String line;
String result = "";
try {
url = new URL(urlToRead);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept-Charset", "UTF-8");
conn.setRequestProperty("Content-Type", "text/xml; charset=UTF-8");
rd = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
while ((line = rd.readLine()) != null) {
byte [] b = line.getBytes();
result += new String(b, "UTF-8");
}
rd.close();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}我用下面的代码显示这个结果:
response.setContentType("text/plain; charset=UTF-8");
PrintWriter out = new PrintWriter(new OutputStreamWriter(response.getOutputStream(), "UTF-8"), true);
try {
String query = request.getParameter("query");
String type = request.getParameter("type");
String res = getHTML(url);
out.write(res);
} finally {
out.close();
}但是响应仍然没有被编码为UTF-8。我做错了什么?
提前谢谢。
发布于 2013-04-08 06:34:42
打给line.getBytes()的电话看起来很可疑。如果您确定返回的内容是UTF-8编码的,那么您可能应该将其设为line.getBytes("UTF-8")。此外,我甚至不确定为什么它是必要的。从BufferedReader中获取数据的典型方法是使用StringBuilder继续将从readLine检索到的每个String附加到结果中。在String和byte[]之间来回转换是不必要的。
将result更改为StringBuilder并执行以下操作:
while ((line = rd.readLine()) != null) {
result.append(line);
}发布于 2013-04-08 06:43:43
这里是您打破字符编码转换链的地方:
while ((line = rd.readLine()) != null) {
byte [] b = line.getBytes(); // NOT UTF-8
result += new String(b, "UTF-8");
}从String#getBytes() javadoc:
使用平台的默认字符集将此字符串编码为字节序列,并将结果存储到新的字节数组中
而且,默认字符集可能不是UTF-8。
但是为什么所有的转换都放在首位呢?只需从源文件读取原始字节,并将原始字节写入消费者即可。它应该是UTF-8格式的。
发布于 2015-03-04 22:26:01
我在另一个场景中也遇到了同样的问题,但只要这样做我相信它会起作用的:
byte[] b = line.getBytes(UTF8_CHARSET);在while循环中:
while ((line = rd.readLine()) != null) {
byte [] b = line.getBytes(); // NOT UTF-8
result += new String(b, "UTF-8");
}https://stackoverflow.com/questions/15868314
复制相似问题