3

Trying to make a simple get request using java.net.http.HttpClient. it works without the proxy usage. Proxy is valid and working. Proxy supports https/s and socks5 connections. However when i try to use the proxy as in the example, receiving this error:

 java.io.IOException: HTTP/1.1 header parser received no bytes

I think i pass proxy into the client correctly (as in example here https://openjdk.java.net/groups/net/httpclient/recipes.html ), although i pass the proxy IP, not the domain, which is seems to be accepted by InetSocketAddress.

example:

                HttpRequest request = HttpRequest.newBuilder()
                        .uri(new URI("http://google.com"))
                        .headers("Content-Type", "application/json;charset=UTF-8")
                        .GET()
                        .build();

                HttpResponse<String> response = HttpClient
                        .newBuilder()
                        .connectTimeout(Duration.ofSeconds(15))
                        .proxy(ProxySelector.of(
                            new InetSocketAddress(
                                    "1.1.1.1", 1111
                            )
                        ))
                        .build()
                        .send(request, HttpResponse.BodyHandlers.ofString());
user1935987
  • 3,136
  • 9
  • 56
  • 108
  • could you also double check that you are actually hitting the proxy ? and whether the proxy responses back / get a response from google ? – AntJavaDev Dec 18 '19 at 05:46
  • i don't think i'm actually hitting the proxy and this `HTTP/1.1 header parser received no bytes` probably means that the client wasn't setup correctly -> proxy wasnt setup correctly – user1935987 Dec 18 '19 at 07:44
  • hmm take a look at [this answer](https://stackoverflow.com/questions/44821561/how-to-set-proxy-host-on-httpclient-request-in-java?noredirect=1&lq=1), dont know if its using the latest `HttpClient`, but surely there must be a way getting the client conf. Also a second thought, because i am seeing some other questions, if you can trace the actual http response, in case it does not have a header, then the `HttpClient` fails to parse the response – AntJavaDev Dec 18 '19 at 08:42
  • thats answer uses apache's `HttpClient`, not `java.net.http` – user1935987 Dec 18 '19 at 15:19

1 Answers1

6

In my case, I fixed it by setting the preferred protocol to HTTP 1.1.

HttpClient.newBuilder()
    .version(Version.HTTP_1_1)
Joe Daley
  • 45,356
  • 15
  • 65
  • 64