Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing OS proxy settings using java

Can I set/change proxy settings in my Windows 7 using java application?

I am trying to use:

public static void setProxy(String proxyUrl, String proxyPort){
    System.getProperties().put("proxySet", "true");
    System.getProperties().put("http.proxyHost", proxyUrl);
    System.getProperties().put("http.proxyPort", proxyPort);
}

but after run my settings doesn't changed and i have the same IP i had before.

like image 353
Domin1992 Avatar asked May 30 '26 03:05

Domin1992


1 Answers

Even though most of the languages does not allow (or) discourage to change the environment variables through program, you can achieve that with JNI in java using setenv() and using ProcessBuilder().

But why do you want to change something for every one from your program? Instead change the variables in your program context like setting the proxy server so that it could be effective only for your program run time context. That's how the applications should be designed and programmed.

Here is an example, off the top of head.

 public static void main(String[] args) throws Exception
    {
        ProcessBuilder processBuilder = new ProcessBuilder("CMD.exe", "/C", "SET");
        processBuilder.redirectErrorStream(true);
        Map<String,String> environment = processBuilder.environment();

        //Set the new envrionment varialbes here
        environment.put("proxySet", "true");
        environment.put("http.proxyHost", proxyUrl);
        environment.put("http.proxyPort", proxyPort);

        Process process = processBuilder.start();
        BufferedReader inputReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
        String dataLog=null;
        while ((dataLog = inputReader.readLine()) != null)
        {
            //Just to see what's going on with process
            System.out.println(dataLog);
        }
    }

Note: Again, discourage the practice of changing environment variables from your program, instead set the required ones for just your context.

like image 80
K139 Avatar answered May 31 '26 17:05

K139



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!