Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Append relative URL to java.net.URL

Tags:

java

url

Provided I have a java.net.URL object, pointing to let's say

http://example.com/myItems or http://example.com/myItems/

Is there some helper somewhere to append some relative URL to this? For instance append ./myItemId or myItemId to get : http://example.com/myItems/myItemId

like image 487
fulmicoton Avatar asked Sep 21 '11 10:09

fulmicoton


People also ask

What is relative URL in Java?

Relative URLs are frequently used within HTML pages. For example, if the contents of the URL: http://java.sun.com/index.html contained within it the relative URL: FAQ.html it would be a shorthand for: http://java.sun.com/FAQ.html. The relative URL need not specify all the components of a URL.

How do you hit a URL in Java?

In your Java program, you can use a String containing this text to create a URL object: URL myURL = new URL("http://example.com/"); The URL object created above represents an absolute URL. An absolute URL contains all of the information necessary to reach the resource in question.

What is Java net URL in Java?

Explanation. public URL(String url ) This constructor creates an object of URL class from given string representation. public URL(String protocol, String host, int port, String file) This constructor creates an object of URL from the specified protocol, host, port number, and file.

What does URL openConnection do?

openConnection. Returns a URLConnection instance that represents a connection to the remote object referred to by the URL . A new instance of URLConnection is created every time when invoking the URLStreamHandler. openConnection(URL) method of the protocol handler for this URL.


2 Answers

This one does not need any extra libs or code and gives the desired result:

//import java.net.URL; URL url1 = new URL("http://petstore.swagger.wordnik.com/api/api-docs?foo=1&bar=baz"); URL url2 = new URL(url1.getProtocol(), url1.getHost(), url1.getPort(), url1.getPath() + "/pet" + "?" + url1.getQuery(), null); System.out.println(url1); System.out.println(url2); 

This prints:

http://petstore.swagger.wordnik.com/api/api-docs?foo=1&bar=baz http://petstore.swagger.wordnik.com/api/api-docs/pet?foo=1&bar=baz 

The accepted answer only works if there is no path after the host (IMHO the accepted answer is wrong)

like image 82
Christoph Henkelmann Avatar answered Sep 18 '22 14:09

Christoph Henkelmann


URL has a constructor that takes a base URL and a String spec.

Alternatively, java.net.URI adheres more closely to the standards, and has a resolve method to do the same thing. Create a URI from your URL using URL.toURI.

like image 39
Andrew Duffy Avatar answered Sep 19 '22 14:09

Andrew Duffy