Java 11 કે પછીના વર્ઝનમાં ક્લાયન્ટ બિલ્ડર પર ProxySelector સેટ કરો. આખી JVMની પ્રોક્સી પ્રોપર્ટી આમ અકબંધ રહે છે:

import java.net.InetSocketAddress;
import java.net.ProxySelector;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;

public class ProxyExample {
    public static void main(String[] args) throws Exception {
        HttpClient client = HttpClient.newBuilder()
            .proxy(ProxySelector.of(
                new InetSocketAddress("203.0.113.10", 8080)))
            .connectTimeout(Duration.ofSeconds(5))
            .build();

        HttpRequest request = HttpRequest.newBuilder()
            .uri(URI.create("https://example.com/"))
            .timeout(Duration.ofSeconds(15))
            .GET()
            .build();

        HttpResponse<String> response = client.send(
            request, HttpResponse.BodyHandlers.ofString());
        System.out.println(response.statusCode());
        System.out.println(response.body());
    }
}

દસ્તાવેજના એન્ડપોઇન્ટને તમારા HTTP પ્રોક્સીથી બદલો; HTTP પ્રોક્સી યાદી તપાસવા માટે વિકલ્પ આપે છે. ProxySelector.of સોકેટ સરનામું લે છે: હોસ્ટમાં http:// પ્રિફિક્સ ન આપો અને પોર્ટ અલગ આપો। તે HTTP પ્રોક્સી પસંદ કરે છે, પોર્ટ નંબર મુજબ SOCKS નહીં. વિનંતીનો URI સાચું ગંતવ્ય જ રહે છે.

HTTPS આ HTTP પ્રોક્સીમાંથી ટનલ વડે પસાર થઈ શકે છે. ગંતવ્યની સુરક્ષા ઘટાડવાની જરૂર નથી અને આ ગોઠવણીનો અર્થ પ્રોક્સી લિસનર પોતે TLSને ટેકો આપે છે એવો નથી.

ક્લાયન્ટ બિલ્ડરનો જોડાણ ટાઇમઆઉટ જોડાણ બનતી વખતે લાગુ પડે છે; વિનંતીનો પોતાનો ટાઇમઆઉટ છે. બંને સ્પષ્ટ રાખો કારણ કે વિનંતી હાલનું જોડાણ ફરી વાપરી શકે છે. ગંતવ્યના કોઈ જવાબ પહેલાં નેટવર્ક, પ્રમાણીકરણ કે ટનલ એક્સેપ્શન આવી શકે છે, જ્યારે પરત આવેલો ભૂલ સ્ટેટસ હંમેશાં એક્સેપ્શન ઊભું કરે જ એવું નથી.

સમાન રૂટિંગ નીતિની વિનંતીઓ માટે ક્લાયન્ટ ફરી વાપરો જેથી એપને તેના જોડાણ વ્યવસ્થાપનનો લાભ મળે.

સંબંધિત લેખો