ADAL4j java proxy issue - java

I am trying to connect azure using adal4j library for java.But i have to connect through the proxy.Following is the snippet of code
String url = "https://login.microsoftonline.com/tenant_id/oauth2/authorize";
authContext = new AuthenticationContext(url,false,
service);
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("proxyhostname", 443));
authContext.setProxy(proxy);
ClientCredential clientCred = new ClientCredential(XXXX, xxxx);
Future<AuthenticationResult> future = authContext.acquireToken(
clientCred,
null);
authResult = future.get();
Also i have tried with
System.setProperty("http.proxyPort", "80");
System.setProperty("http.proxyUser", "xxxx");
System.setProperty("http.proxyPassword", "xxxx");
System.setProperty("http.proxyHost", "xxxxxxx");
And all the time i am getting this following error
the error is.....java.net.ConnectException: Connection timed out: connect
java.util.concurrent.ExecutionException: java.net.ConnectException: Connection timed out: connect
at java.util.concurrent.FutureTask.report(FutureTask.java:122)
at java.util.concurrent.FutureTask.get(FutureTask.java:188)
at com.toyota.eap.auth.Test.main(Test.java:76)
Caused by: java.net.ConnectException: Connection timed out: connect
Note: This error is only if we have proxy within the office. From outside the office If I ran thisprogramme there is no issue.
Any Thought on this.
Thanks

There were the existed threads to answer the issue for java.net.ConnectException: Connection timed out in using Adal4j with Proxy. Please review ADAL for Java Proxy and Java proxy issues - Connection Timed Out and How do I make HttpURLConnection use a proxy?.
For more details, you can use the function setConnectTimeout of Class URLConnection (refer to http://docs.oracle.com/javase/1.5.0/docs/api/java/net/URLConnection.html) to resolve it, see the picture and code below:
String url = "<url_link for http or https>";
int timeout = 30*1000; // 30 seconds
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("<proxy_host>", <proxy_port>));
// if need to auth for proxy
Authenticator authenticator = new Authenticator() {
public PasswordAuthentication getPasswordAuthentication() {
return (new PasswordAuthentication("<user>",
"<password>".toCharArray()));
}
};
Authenticator.setDefault(authenticator);
// open connection using proxy directly for this connection
// if not, setting in the JVM startup argus or using System.setProperty for app global scope
HttpURLConnection conn = new URL(url).openConnection(proxy); // Also HttpsURLConnection
conn.setConnectTimeout(timeout); // set Timeout
Meanwhile, according to my experience,if the proxy IP and port located on-promise network environment, you can be use it on local environment, but failed on Azure. From this perspective, I think you should confirm the proxy is valid on-promise and Azure firstly.
If the connection can connect and take a long time, it is useful to set the connection timeout property as my references above .

is your proxy https? if so, use jvm arguments https. not http:
HTTPS
-Dhttps.proxyHost=proxy-name-without-https.com -Dhttps.proxyPort=proxy-port
ex. -Dhttps.proxyHost=myproxy.com -Dhttps.proxyPort=2021

Related

HttpURLConnection to HTTPs with proxy

I want to connect to an https:// URL in Java that requires proxy.
I have 2 proxies in the system:
HTTP -> proxy.teatre.guerrilla:8080
HTTPS -> proxy.teatre.guerrilla:8443
I've tried with
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("proxy.teatre.guerrilla", 8080));
URL url = new URL ( urlStr);
HttpURLConnection conn = (HttpURLConnection) url.openConnection(proxy);
But I got a Exception in thread "main" java.net.ConnectException: Connection timed out: connect
and I haven't seen the type Proxy.Type.HTTPS
I also tried
System.setProperty("http.proxyHost", "proxy.teatre.guerrilla");
System.setProperty("http.proxyPort", "8080");
System.setProperty("https.proxyHost", "proxy.teatre.guerrilla");
System.setProperty("https.proxyPort", "8443");
with the same result.
I also tried to add this as Program arguments and VM arguments....
-Dhttp.proxyHost=proxy.teatre.guerrilla -Dhttp.proxyPort=8800 -Dhttps.proxyHost=proxy.teatre.guerrilla -Dhttps.proxyPort=8443
please try
System.setProperty("http.proxyHost", "proxy.teatre.guerrilla");
System.setProperty("http.proxyPort", 8080);
You better not include proxy handling in your code. You never know in which environment your JAVA application will be running. So please configure the PROXY settings with JVM args like that: How do I set the proxy to be used by the JVM

Server Timeout on Http GET on certain network

I am trying to make a get request in Java using HttpURLConnection. The response is 200 when I am on my home network but on the company nework i am getting a connect timed out error (SocketTimeoutException) I changed the timeout to be 20 seconds and I am still getting this error after a few seconds. The link is available when I view it in the browser on the same network that I am getting the timeout from the Java code, so I could it still be a firewall issue? Or something else? Here is my code:
String USER_AGENT = "Mozilla/5.0";
URL obj = new URL("http://jsonplaceholder.typicode.com/posts/1");
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setConnectTimeout(20000);
con.setRequestMethod("GET");
con.setRequestProperty("User-Agent", USER_AGENT);
int responseCode = con.getResponseCode();
System.out.println("GET Response Code :: " + responseCode);
This is typically an error produced by a firewall in your company's network. But if your browser is able to get to the internet, then your browser is using some proxy (likely the system proxy). So, you have to parametrize the JVM through the standard Java network properties to make it use the system proxy:
java -Djava.net.useSystemProxies=true ...
Or, alternatively, find out which are the system proxy parameters (host, port, user and password) and pass them to the JVM:
java -Dhttp.proxyHost=... -Dhttp.proxyPort=...

What causes HttpHostConnectException?

I have a Auto Complete/type ahead feature on Search for my website. I see that some time their is an exception associated with it. We are using a proxy server.
org.apache.http.conn.HttpHostConnectException: Connection to http://proxy.xyz.com:60 refused
at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:159)
at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:149)
at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:108)
at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:415)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:641)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:576)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:554)
at com.xxx.dd.sone.integration.SearchDAO.getJSONData(SearchDAO.java:60)
at com.xxx.dd.sone.integration.SearchDAO.searchAutoCompleteResults(SearchDAO.java:560)
at com.xxx.dd.sone.presentation.util.SearchAutoCompleteUtil.doGet(SearchAutoCompleteUtil.java:26)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:845)
at weblogic.servlet.internal.StubSecurityHelper$ServletServiceAction.run(StubSecurityHelper.java:242)
at weblogic.servlet.internal.ServletStubImpl.execute(ServletStubImpl.java:352)
at weblogic.servlet.internal.ServletStubImpl.execute(ServletStubImpl.java:236)
at weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.run(WebAppServletContext.java:3254)
at weblogic.servlet.provider.WlsSubjectHandle.run(WlsSubjectHandle.java:57)
at weblogic.servlet.internal.WebAppServletContext.doSecuredExecute(WebAppServletContext.java:2163)
at weblogic.servlet.internal.WebAppServletContext.execute(WebAppServletContext.java:2074)
at weblogic.servlet.internal.ServletRequestImpl.run(ServletRequestImpl.java:1512)
at weblogic.servlet.provider.ContainerSupportProviderImpl$WlsRequestExecutor.run(ContainerSupportProviderImpl.java:255)
at weblogic.work.ExecuteRequestAdapter.execute(ExecuteRequestAdapter.java:22)
at weblogic.kernel.ExecuteThread.execute(ExecuteThread.java:147)
at weblogic.kernel.ExecuteThread.run(ExecuteThread.java:119)
Caused by: java.net.ConnectException: Connection refused
Here is the how i have coded
public HashMap<String, Object> getJSONData(String url)throws Exception {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpParams params = httpClient.getParams();
try {
HttpConnectionParams.setConnectionTimeout(params, 10000);
HttpConnectionParams.setSoTimeout(params, 10000);
} catch (Exception e) {
e.printStackTrace();
throw e;
}
HttpHost proxy = new HttpHost(proxy.xyz.com, 60);
ConnRouteParams.setDefaultProxy(params, proxy);
URI uri;
InputStream data = null;
uri = new URI(url);
HttpGet method = new HttpGet(uri);
HttpResponse response=null;
try {
response = httpClient.execute(method);
}catch(Exception e) {
e.printStackTrace();
throw e;
}
data = response.getEntity().getContent();
Reader r = new InputStreamReader(data);
HashMap<String, Object> jsonObj = (HashMap<String, Object>) GenericJSONUtil.fromJson(r);
return jsonObj;
}
Can any one tell me why i am getting this exception some time only? is this possible that this exception is caused when a search request is made from Android applications as our website don't support a request is being made from android applications
A "connection refused" error happens when you attempt to open a TCP connection to an IP address / port where there is nothing currently listening for connections. If nothing is listening, the OS on the server side "refuses" the connection.
If this is happening intermittently, then the most likely explanations are (IMO):
the server you are talking ("proxy.xyz.com" / port 60) to is going up and down, OR
there is something1 between your client and the proxy that is intermittently sending requests to a non-functioning host, or something.
Is this possible that this exception is caused when a search request is made from Android applications as our website don't support a request is being made from android applications.
It seems unlikely. You said that the "connection refused" exception message says that it is the proxy that is refusing the connection, not your server. Besides if a server was going to not handle certain kinds of request, it still has to accept the TCP connection to find out what the request is ... before it can reject it.
1 - For example, it could be a DNS that round-robin resolves the DNS name to different IP addresses. Or it could be an IP-based load balancer.
In my case the issue was a missing 's' in the HTTP URL. Error was:
"HttpHostConnectException: Connect to someendpoint.com:80 [someendpoint.com/127.0.0.1] failed: Connection refused" End point and IP obviously changed to protect the network.
You must set proxy server for gradle at some time, you can try to change the proxy server ip address in gradle.properties which is under .gradle document

HttpURLConnection returns 503 error when accessed through proxy

I am working on creating a Video sitemap for a site that has hosted videos on Brightcove video cloud. In order to get all the video information from the site, Brightcove suggests to read the response from their url of following form
http://api.brightcove.com/services/library?token="+accountToken+"&page_size=1&command=find_all_videos&output=JSON&get_item_count=true
the output of the url is in JSON, where accountToken is just an identifier of the account.
When I hit the above url with Token in the browser, it gives me the correct response.
I wrote below program snippet to read from that url
URL jsonURL = new URL("http://api.brightcove.com/services/library?token="+accountToken+"&page_size=1&command=find_all_videos&output=JSON&get_item_count=true");
HttpURLConnection connection = (HttpURLConnection) jsonURL.openConnection();
connection.setRequestMethod("GET");
connection.connect();
BufferedReader reader = new BufferedReader(
new InputStreamReader(connection.getInputStream()));
String lineRead = "";
while (reader.ready()) {
lineRead = lineRead + reader.readLine();
}
As my browser uses proxy, I added below code to include proxy settings
System.setProperty("http.proxyHost", "my.proxyurl.com");
System.setProperty("http.proxyPort", "80");
Without using proxy settings, it returns java.net.ConnectException: Connection refused: connect and with proxy it gives me java.io.IOException: Server returned HTTP response code: 503
So my question is , why is it giving me a 503(Service Unavailable) error ? From the browser its working fine.
Update 1:
It seems like an issue with the Network. I pinged the domain and it said "Request Timed out". Working via HTTP though. Looks like an issue with the Firewall.
I think, it may due to your internet connection, I have tried your code I didn't get any 503(Service Unavailable). Check out with different connection connection(without proxy) and it should work. Or you can try it with slightly different approach:
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("host", "port));
conn = new URL(jsonURL).openConnection(proxy);
If you have SOCKS type proxy, change Proxy's constructor parameter to Proxy.Type.SOCKS.
Minor correction to Jamas code
String host="myproxy.com";
int port=8080;
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(host, port));

Java Proxy Authentication

I have a Java webapp, running in Tomcat 6, that loads RSS feeds from remote URLs.
I use Rome to handle the RSS feeds and different formats for me. The connection part looks like like that :
try{
feedSource = new URL(rssObject.getAsset());
}catch(MalformedURLException mue){
logger.error(...);
throw mue;
}
try{
URLConnection connection = feedSource.openConnection();
feed = new SyndFeedInput().build(new XmlReader(connection));
}catch(Exception){handle...}
The code works fine, except at this new client, where they use a proxy.
In order to use the proxy, I set the http.proxyHost and proxyPort system properties :
System.setProperty("http.proxyHost", proxyHost);
System.setProperty("http.proxyPort", proxyPort);
System.setProperty("https.proxyHost", proxyHost);
System.setProperty("https.proxyPort", proxyPort);
HTTP GET is made to the proxy alright, but now I get a HTTP 502 error (bad gateway or something similar).
Analysing the HTTP exchange with Wireshark, I noticed that the proxy is requiring authentication. It sends a HTTP 507. Java is somehow trying to authenticate but it uses the wrong username and passwords. It seems to use the host name as the username, as for the password I don't know.
So I tried to implement the Authenticator method of specifying a username+password :
Authenticator.setDefault(new Authenticator() {
#Override
protected PasswordAuthentication getPasswordAuthentication() {
logger.info(MessageFormat.format("Generating PasswordAuthentitcation for proxy authentication, using username={0} and password={1}.", username, password));
return new PasswordAuthentication(username, password.toCharArray());
}
});
Now my problem is that it is ignored. The getPasswordAuthentication method is never called. I don't see the logging statement in the log file and using Wireshark I can see that it still uses the host name as the user name.
Why ? It seems that java somehow tries to authenticate by itself without consulting the Authenticator.
The proxy seems to be a MS device that uses NTLM for authentication. Is there some built-in mechanism in java to handle this ? The machine on which the app runs is Win Server 2008 R2.
We did the same here for authenticating on a NTLM based proxy.
The authentication on the proxy is actually a normal HTTP Basic Authentication.
We used the following method:
protected URLConnection newURLConnection(URL pURL) throws IOException {
URLConnection urlConnection = super.newURLConnection(pURL);
String auth = new String(Base64.base64Encode(new String("username:password").getBytes()));
auth = "Basic " + auth;
urlConnection.setRequestProperty("Proxy-Connection","Keep-Alive");
urlConnection.setRequestProperty("Proxy-Authorization",auth);
return urlConnection;
}
That, together with the proxy jvm settings, did the trick.
See http://en.wikipedia.org/wiki/Basic_access_authentication.

Categories