使用jetty Http Client发送Https请求时出现NullPointerException

时间:2015-05-05 11:50:21

标签: java https httpclient jetty-9

我使用Jetty HTTP Client(v9.2.5)发送HTTP请求 它适用于HTTP请求{Post,Get,...} 但是,当我发送HTTPS请求帖时,我看到了这个

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";
    }

}

我的功能

fopen()

什么是错的?

2 个答案:

答案 0 :(得分:1)

对于HTTPS,您必须使用httpclient初始化,如下所示:

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

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

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

// Start HttpClient
httpClient.start();

答案 1 :(得分:0)

您应该使用(请参阅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();

(注意:不建议使用this answer中的new SslContextFactory(),而应使用Client()Server()