3

我想使用 JDK 11HttpClient通过 HTTPS 代理执行请求。我试过这段代码来创建客户端:

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

以及生成请求的代码:

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();

但它失败了java.io.IOException: HTTP/1.1 header parser received no bytes

curl我想要执行的等价物是:

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

那行得通。有什么建议么?

4

0 回答 0