https proxy with JDK11 client

Viewed 1102

I'd like to use the JDK 11 HttpClient to perform a request through an HTTPS proxy. I've tried this code to create the client:

HttpClient client = HttpClient
    .newBuilder()
    .proxy(ProxySelector.of(new InetSocketAddress("my.proxy.host",8443)))
    .version(Version.HTTP_1_1)
    .build();

and this code to generate the request:

String auth = new String(Base64.getEncoder().encode("username:password".getBytes()));
var request =
HttpRequest
    .newBuilder(new URI("http://my.internal.host/path"))
    .POST(BodyPublishers.ofString("{\"foo\":\"bar\"}"))
    .header("Proxy-Authorization", "Basic " + auth)
    .header("Content-Type", "application/json")
    .build();

But it fails with java.io.IOException: HTTP/1.1 header parser received no bytes.

The equivalent curl I'd like to perform would be:

curl -XPOST --proxy 'https://username:password@http://my.proxy.host:8443/path' \
  -d '{"foo":"bar"}' \
  -h 'Content-Type: application/json' \
  http://my.internal.host/path

And that works. Any suggestions?

0 Answers
Related