Add statr of work on HTTP client.

This commit is contained in:
md_5 2013-07-04 10:52:54 +10:00
parent 3f476a30b4
commit 924b90e325
3 changed files with 87 additions and 0 deletions

View File

@ -31,5 +31,10 @@
<version>4.11</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>14.0.1</version>
</dependency>
</dependencies>
</project>

View File

@ -1,5 +1,57 @@
package net.md_5.bungee.http;
import com.google.common.base.Preconditions;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.http.DefaultHttpRequest;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.HttpMethod;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.HttpVersion;
import java.net.URI;
import java.net.URISyntaxException;
import lombok.RequiredArgsConstructor;
@RequiredArgsConstructor
public class HttpClient
{
private final EventLoopGroup eventLoop;
public void get(String url)
{
URI uri = null;
try
{
uri = new URI( url );
} catch ( URISyntaxException ex )
{
throw new IllegalArgumentException( "Could not parse url " + url, ex );
}
Preconditions.checkNotNull( uri.getScheme(), "scheme" );
Preconditions.checkNotNull( uri.getHost(), "host" );
boolean ssl = false;
int port = uri.getPort();
if ( port == -1 )
{
switch ( uri.getScheme() )
{
case "http":
port = 80;
break;
case "https":
port = 443;
break;
default:
throw new IllegalArgumentException( "Unknown scheme " + uri.getScheme() );
}
}
new Bootstrap().channel( NioSocketChannel.class ).group( eventLoop ).handler( new HttpInitializer( url, port, ssl ) ).remoteAddress( uri.getHost(), port ).connect();
HttpRequest request = new DefaultHttpRequest( HttpVersion.HTTP_1_1, HttpMethod.GET, uri.getRawPath() );
request.headers().set( HttpHeaders.Names.HOST, uri.getHost() );
}
}

View File

@ -0,0 +1,30 @@
package net.md_5.bungee.http;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.handler.codec.http.HttpClientCodec;
import io.netty.handler.ssl.SslHandler;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLEngine;
import lombok.RequiredArgsConstructor;
@RequiredArgsConstructor
public class HttpInitializer extends ChannelInitializer<Channel>
{
private final String host;
private final int port;
private final boolean ssl;
@Override
protected void initChannel(Channel ch) throws Exception
{
if ( ssl )
{
SSLContext context = SSLContext.getDefault();
SSLEngine engine = context.createSSLEngine( host, port );
ch.pipeline().addLast( "ssl", new SslHandler( engine ) );
}
ch.pipeline().addLast( "http", new HttpClientCodec() );
}
}