-2

I an developing a web browser. Is there a built-in way to convert partial url strings like "example.com" or "www.example.com" etc... to "http://www.example.com/" ?

Sahar Avr
  • 131
  • 8

3 Answers3

0

I don't know for certain if this will solve your issue - but I might recommend using the build in URL classes to attempt to solve this problem. Please take a look at the links below and decide if they are helpful.

https://docs.oracle.com/javase/tutorial/networking/urls/

Building an absolute URL from a relative URL in Java

http://docs.oracle.com/javase/7/docs/api/java/net/URL.html

Community
  • 1
  • 1
Sh4d0wsPlyr
  • 948
  • 12
  • 28
0

Assuming you are trying to operate on a String typed into the location bar of your web browser then the only thing you can do with confidence is to check whether the string already begins with "http://" or "https://" or some other scheme (such as "ftp://") and, if it does not, prepend "http://" to the start.

As has been mentioned in the comments, it is wrong to assume that the subdomain should be set to "www" because not all web servers have configured this subdomain. (And it's easy for a web server to be configured to redirect a request to the "www" subdomain if the website owner prefers.)

So I'd say the code you need is simply this:

// Create a static final class field.
static final Pattern STARTS_WITH_SCHEME = Pattern.compile("^ *[a-z]+://");

// Then within your method code make use of the Pattern.
if (!STARTS_WITH_SCHEME.matcher(urlString).find()) {
    urlString = "http://" + urlString.trim();
}

This will check whether your urlString begins with any scheme followed by a colon and double-slash. If not, then "http://" will be prepended to your urlString. Note that the Pattern allows spaces to appear at the very start of the urlString and then the method code trims them away.

Bobulous
  • 12,967
  • 4
  • 37
  • 68
-1

From what I've understood from your question,this is what you pretend.

String url = "www.example.com"

//Checks if the string does not start with http://
if (!url.startsWith("http://" && !url.endsWith("/") {
    //Appends the http in the begginning of the String
    url.insert(0, "http://");
}
//Checks if the string does not end with /
if (!url.endsWith("/") {
    //Appends the slash in the end of the url
    url.append("/");
}

Note that I added the verification of the url String, because in some cases I guess you have no certainty of the url format.

Bruno Caceiro
  • 7,035
  • 1
  • 26
  • 45