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
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.
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.
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.
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.
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)
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With