MCPcopy Create free account
hub / github.com/5zig/The-5zig-Mod / HttpClient

Class HttpClient

Utils/src/eu/the5zig/util/io/http/HttpClient.java:19–76  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

17import java.util.concurrent.TimeUnit;
18
19public 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}

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected