java - Netty HTTP 客户端身份验证

标签 java netty

看下面我写的测试代码。 我使用纯 java 设置了一个身份 validator 并进行 URI 调用以获取一些 xml 数据并将其转换为对象。

我编写了下面的代码来测试 hotpotato(netty)与纯 java(无管道)的性能。

问题是,我不知道如何使用 hotpotato 或 netty 验证我的请求,两者的代码都是可以接受的,我只是想测试性能差异(即看看 5 秒内将执行多少个请求) .

    public static void main(String[] args) throws Exception {
        Authenticator.setDefault(new MyAuthenticator("DummyUser", "DummyPassword"));

        int timeToTestFor = 5000; //5 seconds;
        int count = 0;
        System.out.println("Start time");
        long starttime = System.currentTimeMillis();
        do {
            URL url = new URL(
                    "http://example.com/rest/GetData.ashx?what=pizza&where=new%20york&visitorId=12345&sessionId=123456");

            SearchResultsDocument doc = SearchResultsDocument.Factory.parse(url);
            count++;
        } while (System.currentTimeMillis() - starttime < timeToTestFor);
        System.out.println("DONE Total count=" + count);

        System.out.println("Netty/Hotpotatoe Start time");
        count = 0;
        starttime = System.currentTimeMillis();
        do {
            // Create & initialise the client
            HttpClient client = new DefaultHttpClient();
            client.init();


            // Setup the request
            HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_0,
                    HttpMethod.GET, "/rest/GetData.ashx?what=pizza&where=new%20york&visitorId=12345&sessionId=123456");

            // Execute the request, turning the result into a String
            HttpRequestFuture future = client.execute("example.com", 80, request,
                    new BodyAsStringProcessor());
            future.awaitUninterruptibly();
            // Print some details about the request
            System.out.println("A >> " + future);

            // If response was >= 200 and <= 299, print the body
            if (future.isSuccessfulResponse()) {
                System.out.println("B >> "+future.getProcessedResult());
            }

            // Cleanup
            client.terminate();
            count++;
        } while (System.currentTimeMillis() - starttime < timeToTestFor);
        System.out.println("DONE Total count=" + count);
    }

最佳答案

这里是仅使用 Netty 进行基本身份验证的工作示例。使用 Jetty 作为需要基本身份验证的服务器进行测试。

import java.net.InetSocketAddress;
import java.util.concurrent.Executors;

import org.jboss.netty.bootstrap.ClientBootstrap;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.channel.Channels;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelHandler;
import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory;
import org.jboss.netty.handler.codec.base64.Base64;
import org.jboss.netty.handler.codec.http.DefaultHttpRequest;
import org.jboss.netty.handler.codec.http.HttpChunkAggregator;
import org.jboss.netty.handler.codec.http.HttpClientCodec;
import org.jboss.netty.handler.codec.http.HttpHeaders;
import org.jboss.netty.handler.codec.http.HttpMethod;
import org.jboss.netty.handler.codec.http.HttpResponse;
import org.jboss.netty.handler.codec.http.HttpVersion;
import org.jboss.netty.util.CharsetUtil;

public class BasicAuthTest {
private static final int PORT = 80;
private static final String USERNAME = "";
private static final String PASSWORD = "";
private static final String URI = "";
private static final String HOST = "";

public static void main(String[] args) {

    ClientBootstrap client = new ClientBootstrap(
            new NioClientSocketChannelFactory(
                    Executors.newCachedThreadPool(),
                    Executors.newCachedThreadPool()));

    client.setPipelineFactory(new ChannelPipelineFactory() {

        @Override
        public ChannelPipeline getPipeline() throws Exception {
            ChannelPipeline pipeline = Channels.pipeline();
            pipeline.addLast("codec", new HttpClientCodec());
            pipeline.addLast("aggregator", new HttpChunkAggregator(5242880));
            pipeline.addLast("authHandler", new ClientMessageHandler());
            return pipeline;
        }
    });

    DefaultHttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, URI);

    request.addHeader(HttpHeaders.Names.HOST, HOST);

    String authString = USERNAME + ":" + PASSWORD;
    ChannelBuffer authChannelBuffer = ChannelBuffers.copiedBuffer(authString, CharsetUtil.UTF_8);
    ChannelBuffer encodedAuthChannelBuffer = Base64.encode(authChannelBuffer);
    request.addHeader(HttpHeaders.Names.AUTHORIZATION, encodedAuthChannelBuffer.toString(CharsetUtil.UTF_8));

    client.connect(new InetSocketAddress(HOST, PORT)).awaitUninterruptibly().getChannel()
            .write(request).awaitUninterruptibly();

}

public static class ClientMessageHandler extends SimpleChannelHandler {
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception {
        e.getCause().printStackTrace();
    }

    @Override
    public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
        HttpResponse httpResponse = (HttpResponse) e.getMessage();
        String json = httpResponse.getContent().toString(CharsetUtil.UTF_8);
        System.out.println(json);
    }
}

}

关于java - Netty HTTP 客户端身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7609691/

相关文章:

java - 我的自定义 netty 解码器中的 IllegalReferenceCount

java - 我可以在字符串数组中保存字符串变量吗? ( java )

java - Firebase - 具有自定义字段名称的 getValue()

java - 如何在其他类中读取netty中的消息

java - 扩展 DefaultChannelGroup

android - Android 上的 Proguard 和 Netty

java - Netty 比 Tomcat 慢

java - [Json][Java] 对如何解析此文本一无所知。使用库

java - RadioButtons 和 boolean 值连接出现问题

java - 隐藏 Jackson 序列化中的 protected 字段