我正在尝试构建一个原始的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;
}