gpt4 book ai didi

java - 调用 request.getReader() 后重置 HttpRequest

转载 作者:搜寻专家 更新时间:2023-10-30 19:54:15 26 4
gpt4 key购买 nike

有没有一种方法可以在 HttpRequest 上调用 getReader() 方法,然后“重置”请求以便其他调用 getReader() 不会抛出 java.lang.IllegalStateException?

最佳答案

就像其他人所说的那样,不,我认为没有办法重置请求。

在继续之前,我一直处于想要在 ServletFilter 中记录请求内容的相同情况。这是一个forum post这帮助我弄清楚了如何创建像 Stephen C 所说的那样的 HttpServletRequestWrapper。这将存储数据,以便您可以多次调用 getReader()getInputStream()

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;

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

public class MyRequestWrapper extends HttpServletRequestWrapper {

private HttpServletRequest original;
private byte[] reqBytes;
private boolean firstTime = true;

public MyRequestWrapper(HttpServletRequest request) {
super(request);
original = request;
}

@Override
public BufferedReader getReader() throws IOException{

if(firstTime)
firstTime();

InputStreamReader isr = new InputStreamReader(new ByteArrayInputStream(reqBytes));
return new BufferedReader(isr);
}

@Override
public ServletInputStream getInputStream() throws IOException {

if(firstTime)
firstTime();

ServletInputStream sis = new ServletInputStream() {
private int i;

@Override
public int read() throws IOException {
byte b;
if(reqBytes.length > i)
b = reqBytes[i++];
else
b = -1;

return b;
}
};

return sis;
}

private void firstTime() throws IOException{
firstTime = false;
StringBuffer buffer = new StringBuffer();
BufferedReader reader = original.getReader();
String line;
while((line = reader.readLine()) != null){
buffer.append(line);
}
reqBytes = buffer.toString().getBytes();
}
}

关于java - 调用 request.getReader() 后重置 HttpRequest,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6322462/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com