Reputation: 199
Given a url, let say : "example.com"
How do I know if it is http://www.example.com or https://www.example.com in Java or at client side in javascript.
I want to do it for arbitrary domain, on my domain. I am creating a website scanning tool , and I want to find the protocol of website entered by user(in case user enters example.com without https)
Upvotes: 1
Views: 3790
Reputation: 718826
There are a number of misconceptions here.
The string "example.com" is not a URL. It doesn't have a protocol.
A domain is just that. A domain. It is not a URL. It is not a website. It is just a sequence of characters that the DNS can resolve to ... something.
You can't assume that there is any website associated with a domain.
The "www." convention is redundant, old fashioned and ... (IMO) ... ugly. Most places who use "www.example.com" will also have a server at "example.com", and one will redirect to the other as appropriate.
You can't always assume that the server is on the standard port (80 or 443). It is even possible that an https server uses port 80 or an http server uses 443. (Crazy ... but possible)
So how do you figure out if a given domain name has an associated website, what the website's URL is, and whether it is "http:" or "https:"?
Trial and error. There is no other way.
Try send an HTTP request on the standard port and possibly common alternative ports; e.g. port 8080. If you get a valid response, you have identified a HTTP server.
Try the same with an HTTPS request.
If the domain name doesn't start with "www." try prefixing it with that.
But resign yourself to the possibility that none of the above work.
Upvotes: 5
Reputation: 93
You could verify document.location.protocol
to see if it's "http:" or "https:" or consult this page Parsing a URL on java
import java.net.*;
import java.io.*;
public class ParseURL {
public static void main(String[] args) throws Exception {
URL aURL = new URL("http://example.com:80/docs/books/tutorial"
+ "/index.html?name=networking#DOWNLOADING");
System.out.println("protocol = " + aURL.getProtocol());
}
}
Upvotes: 0
Reputation: 4394
in javascript you can do something like this:
console.log(window.location.protocol)
and that will log http or https
Upvotes: 1
Reputation: 1401
You can check the location.protocol
if (location.protocol === 'https:') {
// is https
} else {
// is http
}
Upvotes: 5