2

So I'm trying to make a very basic web browser that accomplishes very specific tasks. However, I need to get the URL from relative URLs (such as in tags. I can get both URLs, but I'm not sure how to approach relative URLs.

I am using Java 6 for compatibility with older systems (a lot older)

Basically, I have the URL "http://example.com/directory/page.html", then I have an tag with the href= "newpage.html". I want to be able to get the URL "http://example.com/directory/newpage.html".

Moreover, if its href= "../newpage.html", I want to get "http://example.com/newpage.html",

and if its href="http://example.org/dir/anotherpage.html", I want to get the URL "http://example.org/dir/anotherpage.html".

Is there any good, clean way of doing this?

1
  • 1
    Convert it to a URI and use its methods, then convert it back. You don't have to worry about the double dots. The Web server will understand them. Commented Mar 24, 2019 at 21:39

2 Answers 2

1

You can simply use the uri.resolve() method.

First create a URI from the base URL you loaded in Browser:

URI uri = new URI("http://example.com/directory/page.html");
URI newpage = uri.resolve("newpage.html");
System.out.println(newpage);

This will print:

http://example.com/directory/newpage.html

The result for uri.resolve("../newpage.html") is :

http://example.com/newpage.html

The result for uri.resolve("http://example.org/dir/anotherpage.html") is:

http://example.org/dir/anotherpage.html

Of course you could check for an http prefix before and return the absolute URL instead of using uri.resolve().

Even the usage of anchors, like #myanchor is possible. The result of uri.resolve("#myanchor") is:

http://example.com/directory/page.html#myanchor

Sign up to request clarification or add additional context in comments.

1 Comment

Worked exactly how I wanted! Thank you!
0

Take a look at Norconex commons-lang and the URLNormalizer. Examine how the method removeDotSegments() is implemented if you want to write the code yourself.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.