Java ResponseReaderWrapper 实现:重复读取响应流
下面是一个可能的实现 ResponseReaderWrapper 的示例:
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
public class ResponseReaderWrapper extends InputStream {
private InputStream wrappedStream;
private byte[] responseBytes;
public ResponseReaderWrapper(InputStream wrappedStream) throws IOException {
this.wrappedStream = wrappedStream;
this.responseBytes = readBytesFromStream(wrappedStream);
}
private byte[] readBytesFromStream(InputStream inputStream) throws IOException {
byte[] buffer = new byte[8192];
int bytesRead;
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
return outputStream.toByteArray();
}
@Override
public int read() throws IOException {
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(responseBytes);
return byteArrayInputStream.read();
}
@Override
public int read(byte[] b) throws IOException {
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(responseBytes);
return byteArrayInputStream.read(b);
}
@Override
public int read(byte[] b, int off, int len) throws IOException {
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(responseBytes);
return byteArrayInputStream.read(b, off, len);
}
@Override
public long skip(long n) throws IOException {
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(responseBytes);
return byteArrayInputStream.skip(n);
}
@Override
public int available() throws IOException {
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(responseBytes);
return byteArrayInputStream.available();
}
@Override
public void close() throws IOException {
wrappedStream.close();
}
@Override
public synchronized void mark(int readlimit) {
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(responseBytes);
byteArrayInputStream.mark(readlimit);
}
@Override
public synchronized void reset() throws IOException {
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(responseBytes);
byteArrayInputStream.reset();
}
@Override
public boolean markSupported() {
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(responseBytes);
return byteArrayInputStream.markSupported();
}
}
这个实现类使用一个字节数组来保存原始响应的内容,并提供了重写 InputStream 的各种读取方法来允许重复读取响应。在构造函数中,它将原始的 InputStream 读取到字节数组中。然后,每个读取方法都创建一个新的 ByteArrayInputStream 对象,并使用该对象来执行实际的读取操作。这样,每次读取都是从字节数组的开头开始,而不是从原始 InputStream 的当前位置开始。
原文地址: https://www.cveoy.top/t/topic/qAqO 著作权归作者所有。请勿转载和采集!