Created by 5zig. All rights reserved � 2015
| 11 | * All rights reserved � 2015 |
| 12 | */ |
| 13 | public class HttpHandler extends SimpleChannelInboundHandler<HttpObject> { |
| 14 | |
| 15 | private final HttpResponseCallback callback; |
| 16 | private final StringBuilder buffer = new StringBuilder(); |
| 17 | private int responseCode = 200; |
| 18 | |
| 19 | public HttpHandler(HttpResponseCallback callback) { |
| 20 | this.callback = callback; |
| 21 | } |
| 22 | |
| 23 | @Override |
| 24 | public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { |
| 25 | try { |
| 26 | callback.call(null, responseCode, cause); |
| 27 | } finally { |
| 28 | ctx.channel().close(); |
| 29 | } |
| 30 | } |
| 31 | |
| 32 | @Override |
| 33 | protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception { |
| 34 | if (msg instanceof HttpResponse) { |
| 35 | HttpResponse response = (HttpResponse) msg; |
| 36 | this.responseCode = response.getStatus().code(); |
| 37 | |
| 38 | if (responseCode == HttpResponseStatus.NO_CONTENT.code()) { |
| 39 | done(ctx); |
| 40 | return; |
| 41 | } |
| 42 | |
| 43 | // if (responseCode != HttpResponseStatus.OK.code()) { |
| 44 | // throw new IllegalStateException("Expected HTTP response 200 OK, got " + response.getStatus()); |
| 45 | // } |
| 46 | } |
| 47 | if (msg instanceof HttpContent) { |
| 48 | HttpContent content = (HttpContent) msg; |
| 49 | buffer.append(content.content().toString(Charset.forName("UTF-8"))); |
| 50 | |
| 51 | if (msg instanceof LastHttpContent) { |
| 52 | done(ctx); |
| 53 | } |
| 54 | } |
| 55 | } |
| 56 | |
| 57 | private void done(ChannelHandlerContext ctx) { |
| 58 | try { |
| 59 | callback.call(buffer.toString(), responseCode, null); |
| 60 | } finally { |
| 61 | ctx.channel().close(); |
| 62 | } |
| 63 | } |
| 64 | } |
nothing calls this directly
no outgoing calls
no test coverage detected