Open browser with proxy setting set from Java - java

I need to open a browser from Java code. I understand this can be done as follows :
java.awt.Desktop.getDesktop().browse(java.net.URI.create("http://google.com"));
But i need the browser to use certain proxy settings as well. (i.e. when the browser opens, its proxy settings must be set to certain values.) I tried using the follwoing code but it doesnt work :
public static void main(String asf[]){
System.setProperty("java.net.useSystemProxies", "true");
System.setProperty("http.proxyHost", "127.0.0.1");
System.setProperty("http.proxyPort", "8080");
try {
java.awt.Desktop.getDesktop().browse(java.net.URI.create("http://google.com"));
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("done");
}
Setting the proxy from command line using
java -Dhttp.proxyHost=webcache.example.com -Dhttp.proxyPort=8080
is not an option for me. How do i accomplish this?

Your code is largely correct which deals with setting the proxy, but in case it is not working there is another way to set the proxy via Java code and that is via the proxy class.
SocketAddress addr = new InetSocketAddress("socks.example.com", 1080);
Proxy proxy = new Proxy(Proxy.Type.SOCKS, addr);
Socket socket = new Socket(proxy);
InetSocketAddress dest = new InetSocketAddress("server.example.org", 1234);
socket.connect(dest);
Here the socket will try to connect to its destination address (server.example.org:1234) through the specified SOCKS proxy.
For more detail you can go through the Standard Java Documentation for Proxies
Your solution for opening a browser can be improved by adding a check
if(Desktop.isDesktopSupported())
{
Desktop.getDesktop().browse(new URI("http://www.google.com"));
}
this is in addition to your solution .... maybe you can call it an alternate way
try {
Process p=Runtime.getRuntime().exec("cmd /c start http://www.google.com");
}
catch(IOException e1) {
System.out.println(e1);
}

The Google Chromes proxy switches can be useful here. We can just make a shortcut for the chrome browser whose target contains the switch --proxy-server=127.0.0.1:8080 . Now this shortcut can be opened from java code using the Runtime class' exec method. The arguments to exec will be "cmd /c start /d \"d:\" chrome.lnk" where d: is the path of my shortcut. A detailed description of this technique can be found here http://sleepingthreads.blogspot.in/2013/07/open-browser-with-proxy-settings-set.html
Note that Google states that the use of switches is not recommended. So use this as a temporary solution only.

Related

BrowserMob Proxy’s - WebDriver / Error: The proxy server is refusing connections

I try to use BrowserMob Proxy’s with WebDriver. I use the next code:
public static void main(String[] args) throws Exception {
String strFilePath = "";
// start the proxy
ProxyServer server = new ProxyServer(4455);
server.start();
//captures the moouse movements and navigations
server.setCaptureHeaders(true);
server.setCaptureContent(true);
// get the Selenium proxy object
Proxy proxy = server.seleniumProxy();
// configure it as a desired capability
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability(CapabilityType.PROXY, proxy);
// start the browser up
WebDriver driver = new FirefoxDriver(capabilities);
// create a new HAR with the label "apple.com"
server.newHar("assertselenium.com");
// open yahoo.com
driver.get("http://assertselenium.com");
driver.get("http://assertselenium.com/2012/10/30/transformation-from-manual-tester-to-a-selenium-webdriver-automation-specialist/");
// get the HAR data
Har har = server.getHar();
FileOutputStream fos = new FileOutputStream(strFilePath);
har.writeTo(fos);
server.stop();
driver.quit();
}
And I got the next error: The proxy server is refusing connections: Firefox is configured to use a proxy server that is refusing connections.
I try also to run the browsermob-proxy.bat with port 4455, and then I get the next error when I run the main:
java.net.BindException: Address already in use: JVM_Bind
How I can use BrowserMob Proxy’s?
The code for stating the proxy seems to be correct. For the BindException, it should be obvious that something is already using the port 4455. You can check it (on Windows machine, written from memory):
netstat -ano | find "4455"
in Linux use lsof -i:4455 to get the PID and kill it.
Anyway, for your proxy refusing connections, try setting the proxy explicitly, see if you have any luck, something like
proxy.setHttpProxy("localhost:4455");
proxy.setSslProxy("localhost:4455");
Also, make sure you are using up-to-date versions of FF and BMP.
java.net.BindException: Address already in use: JVM_Bind
You get this error because on the mentioned port there is already one server running. May be you run your code again without stopping the server you started it at first instance.
Try disabling internet explorer proxy on your pc.

How to set specify proxy for load server application in JVM & Jboss?

I have a load server application which switches between two applications, App1 & App2. Each App has its own IFrame which talks to a bank, but when the bank returns back data, the load server cannot distinguish which app was that. I investigated on that, then I found out that it is the proxy issue.
As a result, I tried to force the application to use proxyHost & proxyport but it did n't work, then I forced the Jboss to use the specific proxyHost & proxyport but it did n't work either. It use a default proxy on the box and it does n't care about my configuration.
Setting the proxyHost & proxyPort at the Jboss startup script (bin\run.bat):
the Jboss logs showed that it had accepted the java VM arguments (e.g. -Dhttp.proxyHost=XX.XX.XX.XX -Dhttp.proxyPort=8080), when we ran
the application, it would still go through the default proxy settings on the box.
I searched in google & stackoverflow and tried different ideas but didn't work.
Could someone please shed some light on it?
Could you try running your apps with the following JVM args: -Dsun.net.inetaddr.ttl=0 -Dnetworkaddress.cache.ttl=0?
The DNS settings get cached after a successful request, these parameters will disable the caching.
You can force an application to ignore any VM arguments for proxyHost and
just use the default proxy of the box it’s running on. You can write a small java program which just prints the default proxy and ran it on the specific box (like this one):
import java.net.InetSocketAddress;
import java.net.ProxySelector;
import java.net.URISyntaxException;
import java.util.Iterator;
import java.util.List;
import java.net.URI;
public class PrintDefaultProxy {
public static void main(String[] args) {
// If you clear these 2 properties then set java.net.useSystemProxies to true, it
// will use the default System Proxy and ignore any settings given to the VM
// e.g. http.proxyHost & http.proxyPort
System.setProperty("http.proxyHost", "");
System.setProperty("http.proxyPort", "");
System.setProperty("java.net.useSystemProxies", "true");
System.out.println("detecting proxies");
List l = null;
try {
String url = "http://google.com.au/";
l = ProxySelector.getDefault().select(new URI(url));
}
catch (URISyntaxException e) {
e.printStackTrace();
}
if (l != null) {
for (Iterator iter = l.iterator(); iter.hasNext();) {
java.net.Proxy proxy = (java.net.Proxy) iter.next();
System.out.println("proxy Type : " + proxy.type());
InetSocketAddress addr = (InetSocketAddress) proxy.address();
if (addr == null) {
System.out.println("No Proxy");
} else {
System.out.println("proxy hostname : " + addr.getHostName());
System.setProperty("http.proxyHost", addr.getHostName());
System.out.println("proxy port : " + addr.getPort());
System.setProperty("http.proxyPort", Integer.toString(addr.getPort()));
}
}
}
}
}
Basically in the code, if you clear the http.proxyHost and http.proxyPort and then set java.net.useSystemProxies to true, it will use
the system default proxy (if any) and ignore any VM arguments.
System.setProperty("http.proxyHost", "");
System.setProperty("http.proxyPort", "");
System.setProperty("java.net.useSystemProxies", "true");
System.out.println("detecting proxies");
Then you run this on your box and passed it some bogus proxy addresss:
C:\t>"C:\Program Files\Java\jdk1.6.0_19\bin\java.exe" -Dhttp.proxyHost=99.0.0.99.9 -Dhttp.proxyPort=8080 PrintDefaultProxy
detecting proxies
proxy Type : DIRECT
No Proxy
Note, if you do not clear those 2 properties, it will use the arguments you pass to the JVM – but from my understanding it’s not what your application seems to be doing. This is a way that the application should ‘just work’ without having to specifically set the proxyHost – and this is most likely why it ignores whatever setting you provide it at the JVM/Jboss level.
When the behaviour is consistent with what you’ve experienced trying to change those settings in Jboss, it means you can’t configure it in an application or Jboss level to use a proxyHost and most likely needs to be done at a Network level.

Why is ProxySelector returning inconsistent results in Java?

8 months ago I used this stack overflow post to automatically use a proxy server in a Java project. It worked beautifully.
Here is the code I came up with at the time:
System.setProperty("java.net.useSystemProxies", "true");
List<Proxy> proxyServers = null;
try {
proxyServers = ProxySelector.getDefault().select(new URI("http://www.twitter.com"));
} catch (URISyntaxException e) {
System.out.println("Error using system proxy");
}
if (proxyServers != null) {
for (Iterator<Proxy> iter = proxyServers.iterator(); iter.hasNext();) {
Proxy proxy = iter.next();
System.out.println("Found Proxy: " + proxy);
InetSocketAddress addr = (InetSocketAddress) proxy.address();
if (addr == null) {
System.out.println("No Proxy");
} else {
System.setProperty("http.proxyHost", addr.getHostName());
System.setProperty("http.proxyPort", Integer.toString(addr.getPort()));
System.out.println("proxy hostname : " + addr.getHostName());
System.out.println("proxy port : " + addr.getPort());
}
}
}
I tried adding this exact same code to another project recently and I get different results. I have my computer setup to use a test proxy server and ran both projects to compare the results. If I run the project from 8 months ago the following is printed out:
Found Proxy: HTTP # 192.168.1.100:8000
proxy hostname : 192.168.1.100
proxy port : 8000
If I run my current project on the same machine with the same Proxy server set up, the following is printed out.
Found Proxy: DIRECT
No Proxy
The only proxy found is a "Direct" and proxy.address() is null.
What would cause this to find the proxy settings in one case but not the other?
Edit:
I fixed this, by moving the code sooner in the startup process, but I don't know why this fixed it.
Probably due to this sentence in http://docs.oracle.com/javase/7/docs/api/java/net/doc-files/net-properties.html#Proxies
java.net.useSystemProxies (default: false) On recent Windows systems
and on Gnome 2.x systems it is possible to tell the java.net stack,
setting this property to true, to use the system proxy settings
(both these systems let you set proxies globally through their user
interface). Note that this property is checked only once at startup.
You can guarantee it working if you put the property in the java command: java -Djava.net.useSystemProxies=true yourclass
Regards
If you will use the code along with secure page, it will not consider the proxy hence it would display Direct and No Proxy.
Try the below code:
proxyServers = ProxySelector.getDefault().select(new URI("http://www.twitter.com"));
proxyServers = ProxySelector.getDefault().select(new URI("https://www.twitter.com"));
you will get the difference.

Groovy URL UnknownHostException on Windows

I'm trying to build a groovy script that connects to a website. The webaddress ends in a non-standard format .abc.
I had this snippet of code working on a Linux box and now I am moving it over to a Windows box. The Windows box throws an UnknownHostException and fails.The website does render in browsers on both Linux and Windows.
def url = 'http://www.testURL.abc'
def connection = new URL(url).openConnection()
if (connection.responseCode != 200)
<<Error Handling>>
I believe it may be a proxy issue since both the Windows and Linux boxes are using different proxies to connect. I looked into this and configured Java on each box to use the proxy of the browser which didn't help either. At this point, I'm somewhat stuck. Any help would be greatly appreciated.
EDIT* Both proxies are using automatic configuration scripts (.pac files)
** Updated syntax errors from copying them over
I ended up finding a solution through the proxy issue. I had to download the automatic configuration script (.pac file) and find out which proxy host and port were being used for my URL.
I had to set the proxy host and port with the following code:
ProxySelector.setDefault(new ProxySelector() {
#Override
public void connectFailed(URI uri, SocketAddress sa, IOException ioe) {
throw new RuntimeException("Proxy connect failed", ioe);
}
#Override
public List select(URI uri) {
return Arrays
.asList(new Proxy(Proxy.Type.HTTP,
new InetSocketAddress(proxyHost,
proxyPort)));
}
});
This was code from unknown host exception

How to get proxy settings from system settings in Java

I'm looking form way how to get system proxy information in Java under Windows, but I've found just one way. But it does not work for me.
public static void main(String[] args) throws Throwable {
System.setProperty("java.net.useSystemProxies", "true");
System.out.println("detecting proxies");
List<Proxy> pl = ProxySelector.getDefault().select(new URI("http://ihned.cz/"));
for (Proxy p : pl)
System.out.println(p);
Proxy p = null;
if (pl.size() > 0) //uses first one
p = pl.get(0);
System.out.println(p.address());
System.out.println("Done");
}
When I run the program, I get:
detecting proxies
DIRECT
null
Done
Java means, that I'm situated directly on internet. But it's wrong. I'm behind proxy. I'm unable to get the solution for my computer.
As we discussed in the comments the proxy settings is just applied for some of browsers you use.
If you want Java to use the same settings you need to manually put it into the java network settings (check this web page for details).
Thanks to Dacwe. The problem is, that browser does not use any system proxy, but it sets proxy self using a script. Thus there are not any proxies in the system and Java cannot reach them.

Categories

Resources