279
技術社區[雲棲]
java web http請求轉發
java web,如何獲取request中的請求參數呢?
/*** * Get request query string * @param request * @return byte[] */ public byte[] getRequestStr(HttpServletRequest request){ int contentLength = request.getContentLength(); byte buffer[] = new byte[contentLength]; for (int i = 0; i < contentLength;) { try { int readlen = request.getInputStream().read(buffer, i, contentLength - i); if (readlen == -1) { break; } i += readlen; } catch (IOException ioexception) { ioexception.printStackTrace(); } finally { // logger.info("Json Request:" + requestPacket); } } return buffer; }
上述方法返回的是byte數組。
下麵的方法直接返回字符串:
/*** * Get request query string * * @param request * @return * @throws UnsupportedEncodingException */ public String getRequestStr(HttpServletRequest request) throws UnsupportedEncodingException{ byte buffer[]=getRequestBytes(request); String charEncoding=request.getCharacterEncoding(); if(charEncoding==null){ charEncoding="UTF-8"; } return new String(buffer,charEncoding); }
應用:上述方法一般用於在filter(javax.servlet.Filter)中獲取請求參數,進行轉發
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(); }
應用:用於在網關中進行請求轉發和響應。
最後更新:2017-04-03 16:48:56