Allow insecure HTTPS connection for Java JDK 11 HttpClient

前端 未结 2 1202
生来不讨喜
生来不讨喜 2020-12-09 10:40

Sometimes it is needed to allow insecure HTTPS connections, e.g. in some web-crawling applications which should work with any site. I used one such solution with old HttpsUR

2条回答
  •  没有蜡笔的小新
    2020-12-09 11:02

    With Java 11, as well you can do a similar effort as mentioned in the selected answer in the link shared with the HttpClient built as:

    HttpClient httpClient = HttpClient.newBuilder()
            .connectTimeout(Duration.ofMillis( * 1000))
            .sslContext(sc) // SSL context 'sc' initialised as earlier
            .sslParameters(parameters) // ssl parameters if overriden
            .build();
    

    with a sample request

    HttpRequest requestBuilder = HttpRequest.newBuilder()
                .uri(URI.create("https://www.example.com/getSomething"))
                .GET()
                .build();
    

    can be executed as:

    httpClient.send(requestBuilder, HttpResponse.BodyHandlers.ofString()); // sends the request
    

    Update from comments, to disable the hostname verification, currently one can use the system property:

    -Djdk.internal.httpclient.disableHostnameVerification
    

    which can be set programmatically as following :-

    final Properties props = System.getProperties(); 
    props.setProperty("jdk.internal.httpclient.disableHostnameVerification", Boolean.TRUE.toString());
    

提交回复
热议问题