我正在尝试构建一个原始的 HTTP POST 请求。但是,我不想实际连接到服务器并发送消息。
我一直在研究 Apache HTTP 库,希望我可以创建一个 HttpPost 对象,设置实体,然后获取它会创建的消息。到目前为止,我可以转储实体,但不能转储整个请求,因为它会出现在服务器端。
有任何想法吗?当然,除了重新创建轮子之外。
解决方案
我将 ShyJ 的响应重构为一对静态类,但原始响应运行良好。这是两个类:
public static final class LoopbackPostMethod extends PostMethod {
private static final String STATUS_LINE = "HTTP/1.1 200 OK";
@Override
protected void readResponse(HttpState state, HttpConnection conn) throws IOException, HttpException {
statusLine = new StatusLine (STATUS_LINE);
}
}
public static final class LoopbackHttpConnection extends HttpConnection {
private static final String HOST = "127.0.0.1";
private static final int PORT = 80;
private final OutputStream fOutputStream;
public LoopbackHttpConnection(OutputStream outputStream) {
super(HOST, PORT);
fOutputStream = outputStream;
}
@Override
public void flushRequestOutputStream() throws IOException { /* do nothing */ }
@Override
public OutputStream getRequestOutputStream() throws IOException, IllegalStateException {
return fOutputStream;
}
@Override
public void write(byte[] data) throws IOException, IllegalStateException {
fOutputStream.write(data);
}
}
这是我用于自己实现的工厂方法,例如:
private ByteBuffer createHttpRequest(ByteBuffer data) throws HttpException, IOException {
LoopbackPostMethod postMethod = new LoopbackPostMethod();
final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
postMethod.setRequestEntity(new ByteArrayRequestEntity(data.array()));
postMethod.execute(new HttpState(), new LoopbackHttpConnection(outputStream));
byte[] bytes = outputStream.toByteArray();
ByteBuffer buffer = ByteBuffer.allocate(bytes.length);
buffer.put(bytes);
return buffer;
}