http client对post内容gzip压缩和server端解压接收

client端代码:

		public void sendHttp(String url, String message) {
			if (StringUtils.isBlank(message)) {
				LOGGER.info("a blank message, return.");
				return;
			}
			PostMethod postMethod = new PostMethod(url);
			postMethod.setContentChunked(true);
			postMethod.addRequestHeader("Accept", "text/plain");
			postMethod.setRequestHeader("Content-Encoding", "gzip");
			postMethod.setRequestHeader("Transfer-Encoding", "chunked");

			try {
				ByteArrayOutputStream originalContent = new ByteArrayOutputStream();
				originalContent
						.write(message.getBytes(Charset.forName("UTF-8")));

				ByteArrayOutputStream baos = new ByteArrayOutputStream();
				GZIPOutputStream gzipOut = new GZIPOutputStream(baos);
				originalContent.writeTo(gzipOut);
				gzipOut.finish();

				postMethod.setRequestEntity(new ByteArrayRequestEntity(baos
						.toByteArray(), "text/plain; charset=utf-8"));
			} catch (IOException e) {
				LOGGER.error("write message fail.", e);
				return;
			}

			int retry = 0;
			do {
				try {
					int status = httpClient.executeMethod(postMethod);
					if (HttpStatus.SC_OK == status) {
						if (LOGGER.isDebugEnabled()) {
							LOGGER.debug("send http success, url=" + url
									+ ", content=" + message);
						}
						return;
					} else {
						String rsp = postMethod.getResponseBodyAsString();
						LOGGER.error("send http fail, status is: " + status
								+ ", response is: " + rsp);
					}
				} catch (HttpException e) {
					LOGGER.info("http exception when send http.", e);
				} catch (IOException e) {
					LOGGER.info("io exception when send http.", e);
				} finally {
					postMethod.releaseConnection();
				}
				LOGGER.info("this is "+ retry + " time, try next");
			} while (retry++ < 3);


server端使用servlet Filter对request请求进行处理,无论后端是哪类web框架都能适配。

/**
 * 
 */
package filter;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

/**
 * 如果请求消息中包含gzip压缩数据,则进行解压
 * 
 * @author chunxi.lcx
 * 
 */
public class GzipFilter implements Filter {

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {

	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		chain.doFilter(new GzipRequestWrapper((HttpServletRequest) request),
				response);
	}

	@Override
	public void destroy() {

	}

}

/**
 * 
 */
package filter;

import java.io.IOException;
import java.util.zip.GZIPInputStream;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author chunxi.lcx
 * 
 */
public class GzipRequestWrapper extends HttpServletRequestWrapper {
	public static final Logger LOGGER = LoggerFactory
			.getLogger(GzipRequestWrapper.class);
	private HttpServletRequest request;

	public GzipRequestWrapper(HttpServletRequest request) {
		super(request);
		this.request = request;
	}

	@Override
	public ServletInputStream getInputStream() throws IOException {
		ServletInputStream stream = request.getInputStream();
		String contentEncoding = request.getHeader("Content-Encoding");
		// 如果对内容进行了压缩,则解压
		if (null != contentEncoding && contentEncoding.indexOf("gzip") != -1) {
			try {
				final GZIPInputStream gzipInputStream = new GZIPInputStream(
						stream);

				ServletInputStream newStream = new ServletInputStream() {

					@Override
					public int read() throws IOException {
						return gzipInputStream.read();
					}
				};
				return newStream;
			} catch (Exception e) {
				LOGGER.debug("ungzip content fail.", e);
			}
		}
		return stream;
	}

}

在web.xml的合适位置配置过滤器:

    <filter>
		<filter-name>GzipFilter</filter-name>
		<filter-class>com.taobao.xray.filter.GzipFilter</filter-class>
	</filter>
	<filter-mapping>
		<filter-name>GzipFilter</filter-name>
		<url-pattern>/metrics/putLines</url-pattern>
	</filter-mapping>



你可能感兴趣的:(压缩,GZip,post)