需求:要让Tomcat在返回200、404等的HttpStatus时,附带自定义消息而不是默认的OK/Not Found。
做法:
- 修改catalina.properties配置文件,添加以下内容。
org.apache.coyote.USE_CUSTOM_STATUS_MSG_IN_HEADER=true
- 在服务器端使用HttpServletResponse.sendError(int, String)发送HttpStatus和自定义消息。
response.sendError(200, "You got the correct result!");
要注意的是当自定义非英文数字的消息时,需要转码成ISO-8859-1。
-
response.sendError(500, new String("亲,你失败了。".getBytes("UTF-8"), "ISO-8859-1"));
相应的在接收时也要转码回来。
-
String responseMsg = new String(conn.getResponseMessage().getBytes("ISO-8859-1"), "UTF-8");