[英]UnsupportedEncodingException when I moved logic to my own class from my Servlet doPost method
When I have this code in my servlet doPost method, everything is fine. 当我的servlet doPost方法中包含此代码时,一切都很好。
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
...
String data = CharStreams.toString(new InputStreamReader(request.getInputStream(), "UTF-8"));
...
}
I wanted to move this code out to another class, but when I did that I get this error that intellij reports: 我想将这段代码移到另一个类,但是当我这样做时,我收到了Intellij报告的错误:
java.io.UnsupportedEncodingException
public class SomeUtil {
public String readFromInput(ServletInputStream is) {
return CharStreams.toString(new InputStreamReader(is, "UTF-8"));
}
}
Does the servlet doPost somewhere handle this exception that I can't see? Servlet doPost是否可以处理我看不到的异常?
The doPost()
method declares throws ServletException, IOException
which covers for the throws UnsupportedEncodingException
in the InputStreamReader constructor you are using. doPost()
方法声明throws ServletException, IOException
覆盖了正在使用的InputStreamReader构造函数中的throws UnsupportedEncodingException
。
In your readFromInput()
method, you could declare a throws
clause as well or surround that line in a try-catch block. 在您的
readFromInput()
方法中,您也可以声明throws
子句,或将该行包含在try-catch块中。 To avoid the UnsupportedEncodingException
, use the constructor that accepts a Charset object and just pass in the standard UTF-8 . 为避免
UnsupportedEncodingException
,请使用接受Charset对象并仅传递标准UTF-8的构造函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.