Netty - 通过ssl发送http请求

时间:2013-09-18 20:00:35

标签: http ssl netty

我正在尝试通过ssl交换http消息的客户端/服务器程序。首先,我创建了使用DefaultHttpRequest成功交换http请求的客户端和服务器程序。发送请求的代码如下所示:

    HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "https://localhost:8443");

    ChannelBuffer buf = ChannelBuffers.copiedBuffer(line, "UTF-8");
    request.setContent(buf);

    request.setHeader(HttpHeaders.Names.HOST, host);
    request.setHeader(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.CLOSE);
    request.setHeader(HttpHeaders.Names.CONTENT_TYPE, "text/xml");
    request.setHeader(HttpHeaders.Names.CONTENT_LENGTH, Integer.toString(buf.capacity()));

    ChannelFuture writeFuture = channel.write(request);

客户端管道工厂包含:

pipeline.addLast("decoder", new HttpResponseDecoder());
pipeline.addLast("encoder", new HttpRequestEncoder());

// and then business logic.
...

服务器管道工厂包含:

pipeline.addLast("decoder", new HttpRequestDecoder());
pipeline.addLast("encoder", new HttpResponseEncoder());

// and then business logic.

...

到目前为止一切顺利。客户端发送,服务器接收并解码请求。使用正确的数据调用我的处理程序上的messageReceived方法。

为了启用SSL,我从SecureChat示例中获取了一些代码并添加到客户端和服务器管道工厂中:

对于服务器:

SSLEngine engine = SecureChatSslContextFactory.getServerContext().createSSLEngine();
engine.setUseClientMode(false);

pipeline.addLast("ssl", new SslHandler(engine));

// On top of the SSL handler, add the text line codec.
pipeline.addLast("framer", new DelimiterBasedFrameDecoder(
        8192, Delimiters.lineDelimiter()));

对于客户:

SSLEngine engine = SecureChatSslContextFactory.getClientContext().createSSLEngine();
engine.setUseClientMode(true);

pipeline.addLast("ssl", new SslHandler(engine));

// On top of the SSL handler, add the text line codec.
pipeline.addLast("framer", new DelimiterBasedFrameDecoder(
        8192, Delimiters.lineDelimiter()));

现在,当我从客户端发送请求时,服务器上似乎什么也没发生。当我启动应用程序时,服务器似乎连接(调用了channelConnected),但是当我发送消息时,没有数据到达服务器(永远不会调用messageReceived)。

我在做什么显然有问题吗?这是https应该工作的方式吗?或者是否有不同的方法通过ssl发送http请求?

谢谢, Weezn

2 个答案:

答案 0 :(得分:0)

您需要在客户端调用SslHandler.handshake()。再次检查它的示例。

答案 1 :(得分:0)

糟糕,似乎我从SecureChat示例中复制并粘贴了太多内容。

删除DelimiterBasedFrameDecoder似乎解决了这个问题。