Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create URL from a String

Tags:

java

http

url

It is a very basic question. But i am unable to find an answer in Java documentation and unable to test it as well since i don't know if such method exist or not.

I might receive a URL String which could be

http://www.example1.com

or

http://www.example1.com/

and then i will get resource path which might start with /api/v1/status.xml or it would be like api/v1/status.xml

I was looking at URL class and I can handle the first part i.e. fetching the hostURL to make it an HTTPS or HTTP request. The problem is appending the resource path. either i have to check it manually if the first letter is / or not. I was wondering if this functionality is already in some class or not.

like image 334
Em Ae Avatar asked Oct 04 '12 15:10

Em Ae


People also ask

How do I find the URL of a path?

The getPath() function is a part of URL class. The function getPath() returns the Path name of a specified URL. Below programs illustrates the use of getPath() function: Example 1: Given a URL we will get the Path using the getPath() function.

What is URL in JavaScript?

url. A string or any other object with a stringifier — including, for example, an <a> or <area> element — that represents an absolute or relative URL. If url is a relative URL, base is required, and will be used as the base URL. If url is an absolute URL, a given base will be ignored. base Optional.


1 Answers

URL url = new URL(yourUrl, "/api/v1/status.xml"); 

According to the javadocs this constructor just appends whatever resource to the end of your domain, so you would want to create 2 urls:

URL domain = new URL("http://example.com"); URL url = new URL(domain + "/files/resource.xml"); 

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

like image 60
Luke Avatar answered Sep 20 '22 08:09

Luke