使用码头 Http 客户端发送 Https 请求中的 NullPointerException

Posted

技术标签:

【中文标题】使用码头 Http 客户端发送 Https 请求中的 NullPointerException【英文标题】:NullPointerException In Send Https Request With jetty Http Client 【发布时间】:2015-05-05 11:50:20 【问题描述】:

我正在使用 Jetty HTTP Client (v9.2.5) 发送 HTTP 请求 它适用于 HTTP 请求 Post,Get,... 但是当我发送 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:642)

我的功能是

private Object sendHttpPOSTRequest(String url, List<Header> headers,
        String content, HttpMethod method) 
    try 
        HttpClient client = new HttpClient();
        client.setMaxConnectionsPerDestination(16);
        client.setAddressResolutionTimeout(5000);
        client.setConnectTimeout(5000);
        client.setMaxRedirects(3);
        client.setFollowRedirects(true);
        client.setExecutor(_executor);
        client.start();
        Request req = client.POST(url).content(
                new StringContentProvider(content));
        if (headers != null)
            req = setHeaders(req, headers);
        req.header(HttpHeader.CONTENT_TYPE, "application/json");

        return req.send();

     catch (Exception e) 
        e.printStackTrace();
        return "Failed";
    


怎么了?

【问题讨论】:

你的客户端在哪里初始化? 你的 _executor 是在哪里定义的? 在类的顶部定义 private ExecutorService _executor = Executors.newCachedThreadPool(); 【参考方案1】:

对于 HTTPS,你必须像下面这样使用 httpclient 初始化:

// Instantiate and configure the SslContextFactory
SslContextFactory.Client sslContextFactory = new SslContextFactory.Client();

// Instantiate HttpClient with the SslContextFactory
HttpClient httpClient = new HttpClient(sslContextFactory);

// Configure HttpClient, for example:
httpClient.setFollowRedirects(false);

// Start HttpClient
httpClient.start();

【讨论】:

【参考方案2】:

你应该使用(见https://www.eclipse.org/jetty/documentation/current/http-client.html):

// Instantiate and configure the SslContextFactory
SslContextFactory.Client sslContextFactory = new SslContextFactory.Client();

// Instantiate HttpClient with the SslContextFactory
HttpClient httpClient = new HttpClient(sslContextFactory);

// Configure HttpClient, for example:
httpClient.setFollowRedirects(false);

// Start HttpClient
httpClient.start();

【讨论】:

以上是关于使用码头 Http 客户端发送 Https 请求中的 NullPointerException的主要内容,如果未能解决你的问题,请参考以下文章

码头 websocket 客户端问题

码头 HTTP/2 客户端示例

如何使用码头设置 2 路 SSL 身份验证连接

java——HttpClient 代理模式发送Http Https(未完成,没贴代码呢)

客户端怎么使用httpclient向https服务器发送数据

HttpComponents 发送post get 请求