p.addLast("handler", new SimpleChannelInboundHandler<HttpObject>(false) {
@Override
public void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
if (msg instanceof FullHttpResponse) {
final FullHttpResponse response = (FullHttpResponse) msg;
final Headers headers = new NettyHeadersBackedHeaders(response.headers());
String contentType = headers.get(HttpHeaderConstants.CONTENT_TYPE.toString());
ByteBuf responseBuffer = initBufferReleaseOnExecutionClose(response.content(), execution);
final ByteBufBackedTypedData typedData = new ByteBufBackedTypedData(responseBuffer, DefaultMediaType.get(contentType));
final Status status = new DefaultStatus(response.getStatus());
int maxRedirects = requestSpecBacking.getMaxRedirects();
String locationValue = headers.get("Location");
URI locationUrl = null;
if (locationValue != null) {
locationUrl = new URI(locationValue);
}
//Check for redirect and location header if it is follow redirect if we have request forwarding left
if (shouldRedirect(status) && maxRedirects > 0 && locationUrl != null) {
Action<? super RequestSpec> redirectRequestConfig = Action.join(requestConfigurer, s -> {
if (status.getCode() == 301 || status.getCode() == 302) {
s.method("GET");
}
s.redirects(maxRedirects - 1);
});
RequestAction requestAction = new RequestAction(redirectRequestConfig, locationUrl, execution, eventLoopGroup, byteBufAllocator, maxContentLengthBytes);
requestAction.execute(fulfiller);
} else {
//Just fulfill what ever we currently have
success(fulfiller, new DefaultReceivedResponse(status, headers, typedData));
}
}
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
ctx.close();
error(fulfiller, cause);
}
});
}
});
ChannelFuture connectFuture = b.connect(host, port);
connectFuture.addListener(f1 -> {
if (connectFuture.isSuccess()) {
String fullPath = getFullPath(uri);
FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.valueOf(requestSpecBacking.getMethod()), fullPath, requestSpecBacking.getBody());
if (headers.get(HttpHeaderConstants.HOST) == null) {
headers.set(HttpHeaderConstants.HOST, host);
}
headers.set(HttpHeaderConstants.CONNECTION, HttpHeaders.Values.CLOSE);
int contentLength = request.content().readableBytes();
if (contentLength > 0) {
headers.set(HttpHeaderConstants.CONTENT_LENGTH, Integer.toString(contentLength, 10));
}
HttpHeaders requestHeaders = request.headers();
for (String name : headers.getNames()) {
requestHeaders.set(name, headers.getAll(name));
}
ChannelFuture writeFuture = connectFuture.channel().writeAndFlush(request);
writeFuture.addListener(f2 -> {
if (!writeFuture.isSuccess()) {