我有一个实用类 TestCracker。它有一个 testInput
方法,该方法接受文本,将请求发送到以该文本作为参数的翻译服务并返回响应 JSON 字符串:
public class TestCracker {
private String ACCESS_TOKEN = "XXXXXXXXXX";
public static void main(String[] args) {
System.out.println(new TestCracker().testInput("Lärm"));
}
public String testInput(String text) {
String translateLink = "https://translate.yandex.net/api/v1.5/tr.json/translate" +
"?key=" + ACCESS_TOKEN + "&text=" + text +
"&lang=de-en" + "&format=plain" + "&options=1";
try {
URL translateURL = new URL(translateLink);
HttpURLConnection connection = (HttpURLConnection) translateURL.openConnection();
setupGETConnection(connection);
connection.connect();
InputStream input = connection.getInputStream();
String inputString = new Scanner(input, "UTF-8").useDelimiter("\\Z").next();
JSONObject jsonObject = new JSONObject(inputString);
return text + "; " + inputString;
}
catch (Exception e) {
System.out.println("Couldn't connect " + e);
return "None";
}
}
private void setupGETConnection(HttpURLConnection connection) throws Exception {
connection.setRequestMethod("GET");
connection.setDoOutput(true);
connection.setInstanceFollowRedirects(false);
}
}
在方法 main
中,我尝试显示字符串 Lärm
的响应 JSON。它工作正常:
Lärm; {"code":200,"detected":{"lang":"de"},"lang":"de-en","text":["Noise"]}
但是,当我尝试使用 Servlet 和浏览器运行并显示相同的内容时,而不仅仅是 IDE:
public class TestServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
String resultPath;
request.setCharacterEncoding("UTF-8");
response.getWriter().print(request.getParameter("input-text2"));
response.getWriter().println(new TestCracker().testInput(request.getParameter("input-text2")));
}
}
运行时,TestServlet
输出:
LärmLärm; {"code":200,"detected":{"lang":"en"},"lang":"de-en","text":["L?rm"]}
可以看出,单词 Lärm
是从一个表单中获取的 - 响应字符串中的第一个单词正确显示(第一个单词),testInput
也得到了正确的单词(第二个单词),但是翻译服务的响应是错误的(;
之后的部分):服务无法翻译并返回了初始单词的损坏版本: >L?rm
。
我不明白为什么会这样。如果将正确的词传递给方法,哪里会出现错误?如果方法在 IDE 中运行时返回正确的翻译('Noise')?
最佳答案
如果您使用的是 Tomcat,则必须正确设置 URIEncoding
。如果参数在 URL (GET) 上。这必须在定义连接器的 server.xml 中完成。
<Server port="8005" shutdown="SHUTDOWN">
<Service name="Catalina">
<Connector URIEncoding="UTF-8" port="8080"/>
<Engine defaultHost="localhost" name="Catalina">
<Host appBase="webapps" name="localhost"/>
</Engine>
</Service>
</Server>
或者, 如果您不想玩弄服务器设置,请阅读编码支持。
喜欢
response.getWriter()
.println(new TestCracker()
.testInput(
new String(request.getParameter("input-text2").getBytes(),"UTF-8"))
);
response.getWriter().print()
具有默认的 utf-8
打印功能,因此您可以看到具有适当字符的输出。
第一种方法更好,因为它将解决整个应用程序的问题。
关于Java Servlet 翻译API请求编码问题: german characters,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54640544/