Search code examples
javahttpproxyclient

How do I set the HttpClient proxy?


I am trying to create an account checker that loops through a combo list and checks if the account is valid, my problem is that I need to change the proxy every once and a while which is what I am currently struggling with. The problem is that I do not know how to change the proxy in the first place and I have tried countless solutions which did not seem to function.

Here is my current code that runs without a proxy change

ObjectMapper objectMapper = new ObjectMapper();
String requestBody = objectMapper.writeValueAsString(credentials);
            
HttpClient client = HttpClient.newBuilder().build();
HttpRequest request = HttpRequest.newBuilder()
                    .uri(URI.create(url))
                    .POST(HttpRequest.BodyPublishers.ofString(requestBody))
                    .build();


HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());;
String responseString = response.body();
if (!responseString.contains("Invalid")) {
      type = AccType.VALID;
}

The imports that I use

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

What I have tried

Setting the proxy directly from the client object using the proxy method Using different imports (Did not work well with the rest of the import) Random solutions I have tried my self

Notes

  • I am trying to keep the program running as fast as possible
  • I have spent countless hours attempting to find a solution
  • This is for educational purposes, I am not going to be releasing this anywhere
  • Please be nice to me

Solution

  • Documentation

    1. The java doc has usage example for HttpClient with proxy
    2. HttpClient Doc

    Usage

        HttpClient.newBuilder()
            .proxy(ProxySelector.of(new InetSocketAddress("your proxy host", your proxy port as integer)))
            .build();
    

    If you have auth issues with proxy, please check this answer