Jetty:如何在Jetty客户端使用SSL

时间:2015-10-15 10:47:51

标签: java ssl jetty

我正在使用Jetty开发我的客户端应用程序端。 我没有在服务器部分使用Jetty。 我需要在客户端配置什么才能使用Jetty客户端发送“https”请求?

这就是我为HTTP客户端所做的事情:

httpClient = new HttpClient();
// Configure HttpClient
httpClient.setFollowRedirects(false);

httpClient.start();

Request request = httpClient.newRequest(url);
//code
httpClient.stop();

如果我尝试使用“https”发送请求,则会出现此异常:

java.util.concurrent.ExecutionException: java.lang.NullPointerException
    at org.eclipse.jetty.client.util.FutureResponseListener.getResult(FutureResponseListener.java:118)
    at org.eclipse.jetty.client.util.FutureResponseListener.get(FutureResponseListener.java:101)
    at org.eclipse.jetty.client.HttpRequest.send(HttpRequest.java:653)
    at egm.httpClient.jetty.TestBackend.POST(TestBackend.java:204)
    at egm.httpClient.jetty.TestStep.execute(TestStep.java:77)
    at egm.httpClient.jetty.TestSuite.execute(TestSuite.java:57)
    at egm.httpClient.jetty.TestLauncher.main(TestLauncher.java:139)
Caused by: java.lang.NullPointerException
    at org.eclipse.jetty.io.ssl.SslClientConnectionFactory.newConnection(SslClientConnectionFactory.java:57)
    at org.eclipse.jetty.client.AbstractHttpClientTransport$ClientSelectorManager.newConnection(AbstractHttpClientTransport.java:187)
    at org.eclipse.jetty.io.ManagedSelector.createEndPoint(ManagedSelector.java:411)
    at org.eclipse.jetty.io.ManagedSelector.access$1600(ManagedSelector.java:56)
    at org.eclipse.jetty.io.ManagedSelector$CreateEndPoint.run(ManagedSelector.java:587)
    at org.eclipse.jetty.util.thread.strategy.ExecuteProduceConsume.produceAndRun(ExecuteProduceConsume.java:213)
    at org.eclipse.jetty.util.thread.strategy.ExecuteProduceConsume.execute(ExecuteProduceConsume.java:101)
    at org.eclipse.jetty.io.ManagedSelector.run(ManagedSelector.java:136)
    at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:654)
    at org.eclipse.jetty.util.thread.QueuedThreadPool$3.run(QueuedThreadPool.java:572)
    at java.lang.Thread.run(Unknown Source)

2 个答案:

答案 0 :(得分:10)

您必须将SslContextFactory传递给HttpClient,如下所示:

HttpClient httpClient = new HttpClient(new SslContextFactory());

您甚至可以通过信任所有人来配置SslContextFactory,或者为其提供密钥库:

new SslContextFactory(true);
new SslContextFactory("/path/to/.keystore");

答案 1 :(得分:0)

jetty-11 对我有用

SslContextFactory.Client sslContextFactory = new SslContextFactory.Client();
sslContextFactory.setTrustAll(true); // you might want to think about this first


ClientConnector clientConnector = new ClientConnector();
clientConnector.setSslContextFactory(sslContextFactory);

HttpClient httpClient = new HttpClient(new HttpClientTransportDynamic(clientConnector));
httpClient.start();

有关解释,请查看此处的官方文档https://www.eclipse.org/jetty/documentation/jetty-11/programming-guide/index.html#pg-client-http-configuration-tls