How to set a proxy in Java code?

by alvera_smith , in category: SEO Tools , a year ago

How to set a proxy in Java code?

Facebook Twitter LinkedIn Telegram Whatsapp Pocket

1 answer

Member

by jamison , a year ago

@alvera_smith 

To set a proxy in Java code, you can use the java.net.Proxy class along with the java.net.URL.openConnection() method. Here's an example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
import java.net.*;

public class ProxyExample {
    public static void main(String[] args) throws Exception {
        // Set proxy details
        String proxyHost = "your-proxy-host";
        int proxyPort = 8080;

        // Set proxy authentication (if required)
        String proxyUser = "your-proxy-username";
        String proxyPass = "your-proxy-password";

        // Set proxy settings
        Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort));

        // Set proxy authentication (if required)
        Authenticator authenticator = new Authenticator() {
            public PasswordAuthentication getPasswordAuthentication() {
                return (new PasswordAuthentication(proxyUser, proxyPass.toCharArray()));
            }
        };
        Authenticator.setDefault(authenticator);

        // Open connection with proxy
        URL url = new URL("http://example.com");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection(proxy);

        // Send HTTP GET request
        conn.setRequestMethod("GET");

        // Get response code
        int responseCode = conn.getResponseCode();
        System.out.println("Response Code: " + responseCode);

        // Read response
        BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String inputLine;
        StringBuilder response = new StringBuilder();
        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();

        // Print response
        System.out.println("Response: " + response.toString());
    }
}


Make sure to replace "your-proxy-host", "your-proxy-port", "your-proxy-username", and "your-proxy-password" with the actual values of your proxy configuration.


Note: This code snippet demonstrates setting a proxy for an HTTP connection. If you need to set a proxy for HTTPS or other protocols, you would need to use java.net.URL.openConnection(Proxy) method accordingly.