3

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.

Domin1992
  • 95
  • 1
  • 3
  • 10

2 Answers2

1

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.

K139
  • 3,654
  • 13
  • 17
  • Thank you for your answer. I need it for my browser (chrome/firefox). I need to change system proxy, which affects on my browser. Thereby i could have changeable IP (kind of, i know). – Domin1992 May 29 '15 at 20:38
0

No, this will not work. These are simply properties that can be used by your app. Changing them will change the value only in the context of you app, not the computer.

You can usually pass a Proxy object to calls that may require it such as this post demonstrates.

Community
  • 1
  • 1
user489041
  • 27,916
  • 55
  • 135
  • 204