Skip to content

Instantly share code, notes, and snippets.

@LuciusChen
Last active November 5, 2018 06:04
Show Gist options
  • Save LuciusChen/32a73a3af08308d705c5db15c0f116fb to your computer and use it in GitHub Desktop.
Save LuciusChen/32a73a3af08308d705c5db15c0f116fb to your computer and use it in GitHub Desktop.
对 request 重新封装,使得 request 可以从此从 InputStream 中取值。和 HttpHelper.java 一起使用。
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.Enumeration;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
/**
* 用于将request重新进行封装
*
*
*/
public class WrappedRequest extends HttpServletRequestWrapper
{
private final byte[] body;
public WrappedRequest(HttpServletRequest request)
throws IOException
{
super(request);
body = HttpHelper.getBodyString(request).getBytes(Charset.forName("UTF-8"));
}
public WrappedRequest(HttpServletRequest request, JSONObject extraParam)
throws IOException
{
super(request);
JSONObject json = JSON.parseObject(HttpHelper.getBodyString(request));
json.putAll(extraParam);
body = json.toJSONString().getBytes(Charset.forName("UTF-8"));
}
@Override
public BufferedReader getReader()
throws IOException
{
return new BufferedReader(new InputStreamReader(getInputStream()));
}
@Override
public ServletInputStream getInputStream()
throws IOException
{
final ByteArrayInputStream bais = new ByteArrayInputStream(body);
return new ServletInputStream()
{
@Override
public int read()
throws IOException
{
return bais.read();
}
};
}
@Override
public String getHeader(String name)
{
return super.getHeader(name);
}
@Override
public Enumeration<String> getHeaderNames()
{
return super.getHeaderNames();
}
@Override
public Enumeration<String> getHeaders(String name)
{
return super.getHeaders(name);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment