有一个有趣的问题..我们的防火墙后面有一个wordpress XML / RSS服务,本地化到多个国家,与中国,俄罗斯等完美配合。
为了公开地公开这个服务,我们创建了一个简单的JSP服务,由于某种原因它不会呈现外来字符。
非常感谢任何想法。
<%@ page language="java" contentType="application/xml; charset=utf-8" pageEncoding="utf-8"%>
<%@ page session="false"%>
<%@ page import='java.io.BufferedReader' %>
<%@ page import='java.io.InputStreamReader' %>
<%@ page import='java.io.IOException' %>
<%@ page import='java.io.PrintWriter' %>
<%@ page import='java.net.URL' %>
<%@ page import='java.net.URLConnection' %>
<%
//final String URL_BASE = "http://localhost:8080/index.php/";
final String URL_BASE = "http://INTERNALSERVERIP:8888/index.php/";
final String NL = System.getProperty("line.separator");
BufferedReader br = null;
try
{
String feedName = request.getParameter("name");
// if no feed was specified
if (feedName == null || feedName.trim().length() == 0)
{
feedName = "feed1";
}
// set the URL based off the feed name
String urlStr = URL_BASE + feedName.trim().toLowerCase();
System.out.println("urlStr: " + urlStr);
URL url = new URL(urlStr);
URLConnection urlCon = url.openConnection();
br = new BufferedReader(new InputStreamReader(urlCon.getInputStream()));
String resLine = null;
while ((resLine = br.readLine()) != null)
{
resLine= new String(resLine.getBytes("ISO8859_1"), "UTF8");
out.println(resLine);
}
}
catch (Throwable t)
{
t.printStackTrace(new PrintWriter(out));
}
finally
{
if (br != null)
{
try
{
br.close();
}
catch (IOException ioe)
{}
}
}
%>
答案 0 :(得分:1)
根据Jasper de Vries的建议,使用UTF8字符集创建InputStreamReader(如下所示)。
br = new BufferedReader(new InputStreamReader(urlCon.getInputStream(), "UTF8"));
然后,您不需要在循环中转换字符串的字符集,因此您可以删除/注释它。以下是jsp的修改版本。
<%@ page language="java" contentType="application/xml; charset=utf-8" pageEncoding="utf-8"%>
<%@ page session="false"%>
<%@ page import='java.io.BufferedReader' %>
<%@ page import='java.io.InputStreamReader' %>
<%@ page import='java.io.IOException' %>
<%@ page import='java.io.PrintWriter' %>
<%@ page import='java.net.URL' %>
<%@ page import='java.net.URLConnection' %>
<%
//final String URL_BASE = "http://localhost:8080/index.php/";
final String URL_BASE = "http://INTERNALSERVERIP:8888/index.php/";
final String NL = System.getProperty("line.separator");
BufferedReader br = null;
try
{
String feedName = request.getParameter("name");
// if no feed was specified
if (feedName == null || feedName.trim().length() == 0)
{
feedName = "feed1";
}
// set the URL based off the feed name
String urlStr = URL_BASE + feedName.trim().toLowerCase();
System.out.println("urlStr: " + urlStr);
URL url = new URL(urlStr);
URLConnection urlCon = url.openConnection();
br = new BufferedReader(new InputStreamReader(urlCon.getInputStream(), "UTF8"));
String resLine = null;
while ((resLine = br.readLine()) != null)
{
// resLine= new String(resLine.getBytes("ISO8859_1"), "UTF8");
out.println(resLine);
}
}
catch (Throwable t)
{
t.printStackTrace(new PrintWriter(out));
}
finally
{
if (br != null)
{
try
{
br.close();
}
catch (IOException ioe)
{}
}
}
%>
希望它有所帮助。 :)