1. 程式人生 > >httpClient對post內容gzip壓縮和server端解壓接收

httpClient對post內容gzip壓縮和server端解壓接收

client端程式碼:

  1. publicvoid sendHttp(String url, String message) {  
  2.     if (StringUtils.isBlank(message)) {  
  3.         LOGGER.info("a blank message, return.");  
  4.         return;  
  5.     }  
  6.     PostMethod postMethod = new PostMethod(url);  
  7.     postMethod.setContentChunked(true);  
  8.     postMethod.addRequestHeader("Accept"
    "text/plain");  
  9.     postMethod.setRequestHeader("Content-Encoding""gzip");  
  10.     postMethod.setRequestHeader("Transfer-Encoding""chunked");  
  11.     try {  
  12.         ByteArrayOutputStream originalContent = new ByteArrayOutputStream();  
  13.         originalContent  
  14.                 .write(message.getBytes(Charset.forName("UTF-8"
    )));  
  15.         ByteArrayOutputStream baos = new ByteArrayOutputStream();  
  16.         GZIPOutputStream gzipOut = new GZIPOutputStream(baos);  
  17.         originalContent.writeTo(gzipOut);  
  18.         gzipOut.finish();  
  19.         postMethod.setRequestEntity(new ByteArrayRequestEntity(baos  
  20.                 .toByteArray(), "text/plain; charset=utf-8"
    ));  
  21.     } catch (IOException e) {  
  22.         LOGGER.error("write message fail.", e);  
  23.         return;  
  24.     }  
  25.     int retry = 0;  
  26.     do {  
  27.         try {  
  28.             int status = httpClient.executeMethod(postMethod);  
  29.             if (HttpStatus.SC_OK == status) {  
  30.                 if (LOGGER.isDebugEnabled()) {  
  31.                     LOGGER.debug("send http success, url=" + url  
  32.                             + ", content=" + message);  
  33.                 }  
  34.                 return;  
  35.             } else {  
  36.                 String rsp = postMethod.getResponseBodyAsString();  
  37.                 LOGGER.error("send http fail, status is: " + status  
  38.                         + ", response is: " + rsp);  
  39.             }  
  40.         } catch (HttpException e) {  
  41.             LOGGER.info("http exception when send http.", e);  
  42.         } catch (IOException e) {  
  43.             LOGGER.info("io exception when send http.", e);  
  44.         } finally {  
  45.             postMethod.releaseConnection();  
  46.         }  
  47.         LOGGER.info("this is "+ retry + " time, try next");  
  48.     } while (retry++ < 3);  


server端使用servlet Filter對request請求進行處理,無論後端是哪類web框架都能適配。

  1. /** 
  2.  *  
  3.  */
  4. package filter;  
  5. import java.io.IOException;  
  6. import javax.servlet.Filter;  
  7. import javax.servlet.FilterChain;  
  8. import javax.servlet.FilterConfig;  
  9. import javax.servlet.ServletException;  
  10. import javax.servlet.ServletRequest;  
  11. import javax.servlet.ServletResponse;  
  12. import javax.servlet.http.HttpServletRequest;  
  13. /** 
  14.  * 如果請求訊息中包含gzip壓縮資料,則進行解壓 
  15.  *  
  16.  * @author chunxi.lcx 
  17.  *  
  18.  */
  19. publicclass GzipFilter implements Filter {  
  20.     @Override
  21.     publicvoid init(FilterConfig filterConfig) throws ServletException {  
  22.     }  
  23.     @Override
  24.     publicvoid doFilter(ServletRequest request, ServletResponse response,  
  25.             FilterChain chain) throws IOException, ServletException {  
  26.         chain.doFilter(new GzipRequestWrapper((HttpServletRequest) request),  
  27.                 response);  
  28.     }  
  29.     @Override
  30.     publicvoid destroy() {  
  31.     }  
  32. }  

  1. /** 
  2.  *  
  3.  */
  4. package filter;  
  5. import java.io.IOException;  
  6. import java.util.zip.GZIPInputStream;  
  7. import javax.servlet.ServletInputStream;  
  8. import javax.servlet.http.HttpServletRequest;  
  9. import javax.servlet.http.HttpServletRequestWrapper;  
  10. import org.slf4j.Logger;  
  11. import org.slf4j.LoggerFactory;  
  12. /** 
  13.  * @author chunxi.lcx 
  14.  *  
  15.  */
  16. publicclass GzipRequestWrapper extends HttpServletRequestWrapper {  
  17.     publicstaticfinal Logger LOGGER = LoggerFactory  
  18.             .getLogger(GzipRequestWrapper.class);  
  19.     private HttpServletRequest request;  
  20.     public GzipRequestWrapper(HttpServletRequest request) {  
  21.         super(request);  
  22.         this.request = request;  
  23.     }  
  24.     @Override
  25.     public ServletInputStream getInputStream() throws IOException {  
  26.         ServletInputStream stream = request.getInputStream();  
  27.         String contentEncoding = request.getHeader("Content-Encoding");  
  28.         // 如果對內容進行了壓縮,則解壓
  29.         if (null != contentEncoding && contentEncoding.indexOf("gzip") != -1) {  
  30.             try {  
  31.                 final GZIPInputStream gzipInputStream = new GZIPInputStream(  
  32.                         stream);  
  33.                 ServletInputStream newStream = new ServletInputStream() {  
  34.                     @Override
  35.                     publicint read() throws IOException {  
  36.                         return gzipInputStream.read();  
  37.                     }  
  38.                 };  
  39.                 return newStream;  
  40.             } catch (Exception e) {  
  41.                 LOGGER.debug("ungzip content fail.", e);  
  42.             }  
  43.         }  
  44.         return stream;  
  45.     }  
  46. }  

在web.xml的合適位置配置過濾器:
  1. <filter>
  2.     <filter-name>GzipFilter</filter-name>
  3.     <filter-class>com.taobao.xray.filter.GzipFilter</filter-class>
  4. </filter>
  5. <filter-mapping>
  6.     <filter-name>GzipFilter</filter-name>
  7.     <url-pattern>/metrics/putLines</url-pattern>
  8. </filter-mapping>