I am using the OkHttp library to make requests from my application to facebook api, however I need to work on a proxy network, instantiating OkHttpClient() and calling OkHttpClient.newCall(request).execute() I get a timeout message because my proxy stop the request.
After a little research I found the following solution:
int proxyPort = 8080;
String proxyHost = "proxyHost";
final String username = "username";
final String password = "password";
Authenticator proxyAuthenticator = new Authenticator() {
#Override public Request authenticate(Route route, Response response) throws IOException {
String credential = Credentials.basic(username, password);
return response.request().newBuilder()
.header("Proxy-Authorization", credential)
.build();
}
};
OkHttpClient client = new OkHttpClient.Builder()
.connectTimeout(60, TimeUnit.SECONDS)
.writeTimeout(60, TimeUnit.SECONDS)
.readTimeout(60, TimeUnit.SECONDS)
.proxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort)))
.proxyAuthenticator(proxyAuthenticator)
.build();
This works great, however I would not want to leave the proxy information in the code or in the application.
Is there any way to configure the proxy as environment variable or in some external file where OkHttp would be able to complete the requests?
I would use system environment variables for storing this sensitive configuration. If you do not have property file, system variable would be good option.
You can update you authenticate method to this:
Authenticator proxyAuthenticator = new Authenticator() {
#Override public Request authenticate(Route route, Response response) throws
IOException {
String username = System.getenv("PROXY_USERNAME");
String password = System.getenv("PROXY_PASSWORD");
if (username == null || username.isEmpty() || password == null || password.isEmpty() )
throw new IllegalStateException("Proxy information is not defined in system variables");
String credential = Credentials.basic(username, password);
return response.request().newBuilder()
.header("Proxy-Authorization", credential)
.build();
}
};
and remove
final String username = "username";
final String password = "password";
class fields.
Now when you run your application you can define the variables on the computer itself or better to pass them as parameters to you java application. For instance:
java -jar -DPROXY_USERNAME=userName -DPROXY_PASSWORD=password yourJar.jar
Related
I'm very new to automation and I'm trying to write a code in Java to setup remote connection using proxy and okhttp. But, it keeps throwing error:
org.openqa.selenium.SessionNotCreatedException: Unable to create a new remote session. Original error: Too many tunnel connections attempted: 21
Getting the error on the last line of the code snippet, i.e. on the return statement.
Request your help in finding the issue in my code. Below is my code snippet:
Function is being called as below:
General.driver = connectViaProxy(caps);
Implementation of connectViaProxy:
public static AndroidDriver<AndroidElement> connectViaProxy(DesiredCapabilities caps) throws FileNotFoundException, IOException {
String proxyHost = Config.getValue("proxy.host");
int proxyPort = Config.getValueint("proxy.port");
String proxyUserDomain = Config.getValue("proxy.user-domain");
String proxyUser = Config.getValue("proxy.user");
String proxyPassword=EncryptionUtil.passwordDecoder(Config.getValue("proxy.encrypted-password").getBytes());
URL url;
try {
url = new URL("https://"+Config.getValue("BrowserStack.userName")+":"+Config.getValue("BrowserStack.accessKey")+"#hub-cloud.browserstack.com/wd/hub");
} catch (MalformedURLException e) {
throw new RuntimeException(e.getMessage(), e);
}
Authenticator proxyAuthenticator = new Authenticator()
{
#Override
public Request authenticate(Route route, Response response) throws IOException {
String credential = Credentials.basic(proxyUserDomain + "\\" + proxyUser, proxyPassword);
return response.request().newBuilder()
.header("Proxy-Authorization", credential)
.build();
}
};
okhttp3.OkHttpClient.Builder client = new okhttp3.OkHttpClient.Builder()
.connectTimeout(60, TimeUnit.SECONDS)
.writeTimeout(60, TimeUnit.SECONDS)
.readTimeout(60, TimeUnit.SECONDS)
.proxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort)))
.proxyAuthenticator(proxyAuthenticator);
Factory factory = new MyHttpClientFactory(new org.openqa.selenium.remote.internal.OkHttpClient(client.build(), url));
HttpCommandExecutor executor = new AppiumCommandExecutor(MobileCommand.commandRepository, url, factory);
return new AndroidDriver<AndroidElement>(executor, caps);
}
I believe the proxy in your network is not passing the first request made by your test script to establish connection to BrowserStack.
Try to whitelist *.browserstack.com in your proxy for ports 80 and 443.
If that does not work, use local testing and follow the steps from the below documentation so that the request to BrowserStack is by-passed by the proxy.
https://www.browserstack.com/docs/automate/selenium/test-behind-proxy/configure-settings
I am using okhttp3 and trying to see how do I pass userId & pswd to authenticate with proxy server that accepts only HTTPS protocol. I already saw exmaple over SO & on other sites(link below) but they don't have HTTPS protocol.
https://botproxy.net/docs/how-to/okhttpclient-proxy-authentication-how-to/
Can anyone please tell me how to use HTTPS protocol to call proxy server?
It is not officially supported but there is a workaround.
https://github.com/square/okhttp/issues/6561
Authenticator proxyAuthenticator = new Authenticator() {
#Override public Request authenticate(Route route, Response response) throws IOException {
String credential = Credentials.basic(username, password);
return response.request().newBuilder().header("Proxy-Authorization", credential).build();
}
};
OkHttpClient client = new OkHttpClient.Builder()
.proxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort)))
.proxyAuthenticator(proxyAuthenticator);
.socketFactory(new DelegatingSocketFactory(SSLSocketFactory.getDefault()))
.build();
Hi I got proxy 407 authentication error in my spring boot project.I tried two scenario in these scenarios proxyHost and proxyPort values are working but username and password has no effect?Is any one face this scenario?In my local machine when I give port and host and giving no username password,it works my local user and work,but I give username and password in wrong format to see its effect?I doesnt effect.
Also in server I got 407 authentication proxy exception.How can pass proxy username and password in spring boot?thanks
I add jvm parameters but proxyuser and proxyPassword no effect
-Dhttps.proxyHost=something -Dhttps.proxyPort=5555-Dhttps.proxyUser=xxx -Dhttps.proxyPassword=yyy
I also add someproxy code to myresttemplate builder but it has no effect.
RestTemplate restTemplate=new RestTemplateBuilder()
.build();
int proxyPortNum =5555;
String proxyHost="something";
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(new AuthScope(proxyHost, proxyPortNum), new UsernamePasswordCredentials("myname", "333"));
HttpClientBuilder clientBuilder = HttpClientBuilder.create();
clientBuilder.useSystemProperties();
clientBuilder.setProxy(new HttpHost(proxyHost, proxyPortNum));
clientBuilder.setDefaultCredentialsProvider(credsProvider);
clientBuilder.setProxyAuthenticationStrategy(new ProxyAuthenticationStrategy());
CloseableHttpClient client = clientBuilder.build();
HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
factory.setHttpClient(client);
restTemplate.setRequestFactory(factory);
you should try something like this:-----
private RestTemplate createRestTemplate() throws Exception {
final String username = "myname";
final String password = "333";
final String proxyUrl = "something";
final int port = 5555;
HttpHost myProxy = new HttpHost(proxyUrl, port);
HttpClientBuilder clientBuilder = HttpClients.custom();
List<Header> headers = new ArrayList<>();
BasicHeader authHeader = new BasicHeader("Authorization",base64authUserPassword());
headers.add(authHeader);
RequestDefaultHeaders reqHeader = new RequestDefaultHeaders(headers);
clientBuilder.addInterceptorLast(reqHeader);
clientBuilder.setProxy(myProxy).disableCookieManagement();
HttpClient httpClient = clientBuilder.build();
HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
factory.setHttpClient(httpClient);
return new RestTemplate(factory);
}
public String base64authUserPassword() {
byte[] baseencode = Base64.getEncoder().encode((username + ":" + password).getBytes());
return "Basic " + new String(baseencode);
}
Hope it will resolve your issue.
How can I use Socks5 proxy in Okhttp to start http request ?
My code:
Proxy proxy = new Proxy(Proxy.Type.SOCKS, InetSocketAddress.createUnresolved(
"socks5host", 80));
OkHttpClient client = new OkHttpClient.Builder()
.proxy(proxy).authenticator(new Authenticator() {
#Override
public Request authenticate(Route route, Response response) throws IOException {
if (HttpUtils.responseCount(response) >= 3) {
return null;
}
String credential = Credentials.basic("user", "psw");
if (credential.equals(response.request().header("Authorization"))) {
return null; // If we already failed with these credentials, don't retry.
}
return response.request().newBuilder().header("Authorization", credential).build();
}
}).build();
Request request = new Request.Builder().url("http://google.com").get().build();
Response response = client.newCall(request).execute(); <--- **Here, always throw java.net.UnknownHostException: Host is unresolved: google.com**
System.out.println(response.body().string());
How to avoid UnknownHostException?
Any example ?
Thanks!
I found a solution: When create a OkHttpClient.Builder(), set a new socketFactory instead of set proxy, and return a sock5 proxy inside socketFactory createSocket.
I think it's the easiest working soulution. But it seems to me that it can be not 100% safe. I took this code from this code from here and modified it because my proxy's RequestorType is SERVER.
Actually, java has a strange api for proxies, you should to set auth for proxy through system env ( you can see it from the same link)
final int proxyPort = 1080; //your proxy port
final String proxyHost = "your proxy host";
final String username = "proxy username";
final String password = "proxy password";
InetSocketAddress proxyAddr = new InetSocketAddress(proxyHost, proxyPort);
Proxy proxy = new Proxy(Proxy.Type.SOCKS, proxyAddr);
Authenticator.setDefault(new Authenticator() {
#Override
protected PasswordAuthentication getPasswordAuthentication() {
if (getRequestingHost().equalsIgnoreCase(proxyHost)) {
if (proxyPort == getRequestingPort()) {
return new PasswordAuthentication(username, password.toCharArray());
}
}
return null;
}
});
OkHttpClient client = new OkHttpClient.Builder()
.proxy(proxy)
.build();
I want to create my DbxRequestConfig Object with a StandardHttpRequestor, because I need it to use a Proxy.
The Proxy is a http Proxy, Port 80, and needs authentication.
Proxyaddress: http://myproxy.com
Proxyport: 80
Proxyusername: username
Proxypassword: password
So I tried to use the global Java Proxy setup:
System.setProperty("http.proxy","proxyaddress") //... http.proxyUser, http.ProxyPassword
//and so on
It did not work.
After looking into the StandardHttpRequestor I realized I need to use this Object as well as a Proyx Object:
Proxy proxy = new Proxy(Proxy.Type.HTTP,new InetSocketAddress(ip,port));
StandardHttpRequestor requ = new StandardHttpRequestor(proxy);
Which is wrong, because it has no authentication.
For authentication, the net and google show me the following. Putting all together, my current code looks like the following:
String ip = "http://myproxy.com";
int port = 80;
final String authUser = "username";
final String authPassword = "password";
Authenticator.setDefault(new Authenticator() {
#Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(authUser, authPassword.toCharArray());
}
});
System.setProperty("http.proxyUser", authUser);
System.setProperty("http.proxyPassword", authPassword);
Proxy proxy = new Proxy(Proxy.Type.HTTP,new InetSocketAddress(ip,port));
StandardHttpRequestor requ = new StandardHttpRequestor(proxy);
return requ;
But this does not work as well.
What am I doing wrong?
I can't seem to get the Proxy to work.
One problem was the http:// in String ip = "http://myproxy.com";
My current code looks the following, and works sometimes. Sometimes not. I have no idea why. Sometimes I have to reallow the App to be connected to my DropBox Account, because the authKey doesn't come through the proxy...
Well at least I got an example working for you guys having the same trouble. Maybe the rest of the problem is on the proxy side? I'll have a further look into this. But here comes my code:
public HttpRequestor getProxy(){
if("true".equals(config.getProperty("proxy","false"))){
String ip = "proxy.myproxy.com";
int port = 80;
final String authUser = "username";
final String authPassword = "password";
Authenticator.setDefault(new Authenticator() {
#Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(authUser, authPassword.toCharArray());
}
});
Proxy proxy = new Proxy(Proxy.Type.HTTP,new InetSocketAddress(ip,port));
HttpRequestor req = new StandardHttpRequestor(proxy);
return req;
}
return null;
}
As you can see I don't use the StandardHttpRequestor anymore. For the Dropbox code it is the following:
HttpRequestor requ = con.getProxy();
if(requ!=null)
config = new DbxRequestConfig(APP_NAME, Locale.getDefault().toString(),requ);
else
config = new DbxRequestConfig(APP_NAME, Locale.getDefault().toString());
As I already said, sometimes it works. Sometimes not. I'm going to write more info about that as soon as I know if it's because of the code or because of the proxy itself.