Created
January 12, 2016 00:25
-
-
Save NiteshKant/5202f396ac903d2dc0a4 to your computer and use it in GitHub Desktop.
How to add a handler to an HTTP client and read headers.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package io.reactivex.netty.examples.http; | |
import io.netty.buffer.ByteBuf; | |
import io.netty.channel.ChannelDuplexHandler; | |
import io.netty.channel.ChannelHandlerContext; | |
import io.netty.channel.ChannelPromise; | |
import io.netty.handler.codec.http.HttpRequest; | |
import io.reactivex.netty.RxNetty; | |
import io.reactivex.netty.protocol.http.AbstractHttpContentHolder; | |
import io.reactivex.netty.protocol.http.client.HttpClient; | |
import io.reactivex.netty.protocol.http.client.HttpClientRequest; | |
import java.nio.charset.Charset; | |
public class SampleAddHandler { | |
public static void main(String[] args) { | |
RxNetty.createHttpServer(8088, (request, response) -> response.writeStringAndFlush("Hello")).start(); | |
HttpClient<ByteBuf, ByteBuf> client = RxNetty.<ByteBuf, ByteBuf>newHttpClientBuilder("localhost", 8088) | |
.appendPipelineConfigurator(pipeline -> { | |
pipeline.addLast(new ChannelDuplexHandler() { | |
@Override | |
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) | |
throws Exception { | |
if (msg instanceof HttpRequest) { | |
HttpRequest request = (HttpRequest) msg; | |
String headerVal = request.headers().get("Req-Header"); | |
System.out.println("Header val in handler: " + headerVal); | |
} | |
super.write(ctx, msg, promise); | |
} | |
}); | |
}).build(); | |
for (int i = 0; i < 4; i++) { | |
HttpClientRequest<ByteBuf> request = HttpClientRequest.createGet("/hello"); | |
request.getHeaders().add("Req-Header", "value: " + i); | |
client.submit(request) | |
.flatMap(AbstractHttpContentHolder::getContent) | |
.toBlocking() | |
.forEach(byteBuf -> System.out.println(byteBuf.toString(Charset.defaultCharset()))); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment