Created
August 21, 2019 17:53
-
-
Save mminer/35065abfa44f9b45833d5c8c00ec62b1 to your computer and use it in GitHub Desktop.
Servlet request wrapper that allows reading request body multiple times.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.matthewminer; | |
import org.apache.commons.io.IOUtils; | |
import javax.servlet.ReadListener; | |
import javax.servlet.ServletInputStream; | |
import javax.servlet.http.HttpServletRequest; | |
import javax.servlet.http.HttpServletRequestWrapper; | |
import java.io.ByteArrayInputStream; | |
import java.io.IOException; | |
public class MultiReadHttpServletRequest extends HttpServletRequestWrapper { | |
private byte[] cache; | |
public MultiReadHttpServletRequest(HttpServletRequest request) { | |
super(request); | |
try { | |
ServletInputStream inputStream = super.getInputStream(); | |
cache = IOUtils.toByteArray(inputStream); | |
} catch (IOException e) { | |
cache = new byte[0]; | |
} | |
} | |
@Override | |
public ServletInputStream getInputStream() { | |
ByteArrayInputStream inputStream = new ByteArrayInputStream(cache); | |
return new ServletInputStream() { | |
@Override | |
public boolean isFinished() { | |
return inputStream.available() == 0; | |
} | |
@Override | |
public boolean isReady() { | |
return true; | |
} | |
@Override | |
public int read() { | |
return inputStream.read(); | |
} | |
@Override | |
public void setReadListener(ReadListener readListener) { | |
throw new UnsupportedOperationException(); | |
} | |
}; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment