NOTE: This is not a duplicate of https proxy with JDK11 client, which is about a HTTP proxy. My question is about a socks proxy, which requires a different solution. Neither is it a duplicate of How can I use HttpClient-4.5 against a SOCKS proxy?, which is about the Apache HttpClient instead of the JDK HttpClient.
How can I use a socks 5 proxy with java.net.http.HttpClient
?
I tried the code below, but it results in a following exception:
Exception in thread "main" java.io.IOException: HTTP/1.1 header parser received no bytes
at java.net.http/jdk.internal.net.http.HttpClientImpl.send(HttpClientImpl.java:586)
Code:
import java.io.IOException;
import java.net.*;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.Collections;
import java.util.List;
public class ProxyApp {
public static void main(String[] args) throws Exception {
run1();
}
public static void run1() throws Exception {
HttpClient client = HttpClient.newBuilder()
.version(HttpClient.Version.HTTP_1_1)
.proxy(ProxySelector.of(new InetSocketAddress("localhost", 8181)))
.build();
HttpRequest request = HttpRequest
.newBuilder(new URI("http://example.org/"))
.build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
String verificationText = "Example Domain";
// Should print "true" otherwise the request failed
System.out.println(response.body().contains(verificationText));
}
}