Changing OS proxy settings using java
Is it possible to set / change proxy settings on my Windows 7 using a 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 running my settings didn't change and I have the same IP as before.
source to share
While most languages do not allow (or) prevent environment variables from being changed through a program, you can achieve this with JNI in java by using setenv()
and using ProcessBuilder()
.
But why do you want to change something for each of your programs? Instead, change the variables in the context of your program, for example, set a proxy so that it can only be effective for the context of the program's runtime. This is how applications should be designed and programmed.
Here's an example from the top of the 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 going on with process
System.out.println(dataLog);
}
}
Note. Again, remove the practice of changing environment variables from your program, instead set the ones required only for your context.
source to share