| 17 | import java.util.concurrent.TimeUnit; |
| 18 | |
| 19 | public class HttpClient { |
| 20 | |
| 21 | public static final int TIMEOUT = 5000; |
| 22 | private static final Cache<String, InetAddress> addressCache = CacheBuilder.newBuilder().expireAfterWrite(5, TimeUnit.MINUTES).build(); |
| 23 | |
| 24 | @SuppressWarnings("UnusedAssignment") |
| 25 | public static void get(String url, EventLoopGroup eventLoop, final HttpResponseCallback callback) { |
| 26 | Preconditions.checkNotNull(url, "url"); |
| 27 | Preconditions.checkNotNull(eventLoop, "eventLoop"); |
| 28 | Preconditions.checkNotNull(callback, "callBack"); |
| 29 | |
| 30 | final URI uri = URI.create(url); |
| 31 | |
| 32 | Preconditions.checkNotNull(uri.getScheme(), "scheme"); |
| 33 | Preconditions.checkNotNull(uri.getHost(), "host"); |
| 34 | boolean ssl = uri.getScheme().equals("https"); |
| 35 | int port = uri.getPort(); |
| 36 | if (port == -1) { |
| 37 | if (uri.getScheme().equals("http")) |
| 38 | port = 80; |
| 39 | else if (uri.getScheme().equals("https")) |
| 40 | port = 443; |
| 41 | else |
| 42 | throw new IllegalArgumentException("Unknown scheme " + uri.getScheme()); |
| 43 | } |
| 44 | |
| 45 | InetAddress inetHost = addressCache.getIfPresent(uri.getHost()); |
| 46 | if (inetHost == null) { |
| 47 | try { |
| 48 | inetHost = InetAddress.getByName(uri.getHost()); |
| 49 | } catch (UnknownHostException ex) { |
| 50 | callback.call(null, -1, ex); |
| 51 | return; |
| 52 | } |
| 53 | addressCache.put(uri.getHost(), inetHost); |
| 54 | } |
| 55 | |
| 56 | ChannelFutureListener future = new ChannelFutureListener() { |
| 57 | @Override |
| 58 | public void operationComplete(ChannelFuture future) throws Exception { |
| 59 | if (future.isSuccess()) { |
| 60 | String path = uri.getRawPath() + ((uri.getRawQuery() == null) ? "" : "?" + uri.getRawQuery()); |
| 61 | |
| 62 | HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, path); |
| 63 | request.headers().set(HttpHeaders.Names.HOST, uri.getHost()); |
| 64 | |
| 65 | future.channel().writeAndFlush(request); |
| 66 | } else { |
| 67 | callback.call(null, -1, future.cause()); |
| 68 | } |
| 69 | } |
| 70 | }; |
| 71 | |
| 72 | new Bootstrap().channel(NioSocketChannel.class).group(eventLoop).handler(new HttpInitializer(callback, ssl, uri.getHost(), port)). |
| 73 | option(ChannelOption.CONNECT_TIMEOUT_MILLIS, TIMEOUT).remoteAddress(inetHost, port).connect().addListener(future); |
| 74 | } |
| 75 | |
| 76 | } |
nothing calls this directly
no outgoing calls
no test coverage detected