Saturday, August 3, 2019

java - how to check https using HttpURLConnection




I am trying to connect to a url with HttpUrlConnection. the host which user enter can be running on http:// or https://. when i am connecting it throws an exception as EOFException.
Is there any way that i identify that url is running on https through some error code or something ??



Following code i am using for this purpose.



HttpURLConnection.setFollowRedirects(true);
con = (HttpURLConnection) new URL(url[0]).openConnection();
con.setRequestMethod("POST");
con.setConnectTimeout(20000);



I m using the abode code what if the url is not valid like i type wwww.gooooooodldldle.com
which is not valid url. I am getting Java.net.SocketTimeout exception here


Answer



The URL cannot change after the connection has been created if you don't reacreate it again. I would do it like this to know the protocol.



URL url;
try {
url = new URL(url[0]);
if(url.getProtocol().equalsIgnoreCase(HTTPS){

Lod.i(TAG, "Is HTTPS connection");
} else {
Log.i(TAG, "Is HTTP connection");
}
} catch (EOFException eofEx) {
eofEx.printStackTrace();
}


After update:




You can check the url string with a Regular Expresion and then if it's correct try the connection. Or put all the logic inside a try catch and show a toast or dialog if the exception is rised.



Hope it helps.


No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...