Java Web中,重写response应答体(响应体)
- /***
- * Send http request
- *
- * @param response
- * @param bytes :字节数组
- * @param contentType :if is null,default value is "application/json"
- * @param encoding : 编码方式
- * @throws IOException
- */
- public static void sendRequestWriter(HttpServletResponse response, byte[] bytes,
- String contentType,String encoding) throws IOException {
- response.setContentLength(bytes.length);
- if (contentType == null) {
- contentType = "application/json";
- }
- response.setContentType(contentType);
- PrintWriter printer = response.getWriter();
- printer.println(new String(bytes,encoding));
- printer.flush();
- printer.close();
- }
- /***
- *
- * @param response
- * @param sendData :<code>String</code>
- * @param contentType
- * @param encoding : such as GBK/utf-8
- * @throws IOException
- */
- public static void sendRequestWriter(HttpServletResponse response, String sendData,
- String contentType,String encoding) throws IOException {
- // response.setContentLength(sendData.getBytes(encoding).length);
- byte[]bytes=sendData.getBytes(encoding);
- sendRequestWriter(response, bytes, contentType, encoding);
- }
以上方法都是使用PrintWriter来写入response的。
下面的方式是使用流的方式写入response:
- /***
- * test ok
- * @param response
- * @param bytes
- * @param contentType
- * @param encoding
- * @throws IOException
- */
- public static void sendRequestStream(HttpServletResponse response, byte[] bytes,
- String contentType) throws IOException {
- response.setContentLength(bytes.length);
- if (contentType == null) {
- contentType = "application/json";
- }
- response.setContentType(contentType);
- ServletOutputStream sos = response.getOutputStream();
- sos.write(bytes, 0, bytes.length);
- sos.flush();
- sos.close();
- }
应用:用于在网关中进行请求转发和响应。
见附件中的类com.common.util.SystemUtil