Costruire un URL assoluto da un URL relativo in Java
-
21-09-2019 - |
Domanda
Ho problemi a creare un URL assoluto da un URL relativo senza ricorrere all'hacking di stringhe...
Dato
http://localhost:8080/myWebApp/someServlet
All'interno del metodo:
public void handleRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
Qual è il modo più "corretto" di costruire:
http://localhost:8080/myWebApp/someImage.jpg
(Nota, deve essere assoluto, non relativo)
Attualmente lo sto facendo costruendo la stringa, ma DEVE esserci un modo migliore.
Ho esaminato varie combinazioni di nuovi URI/URL e alla fine ho ottenuto
http://localhost:8080/someImage.jpg
Aiuto molto apprezzato
Soluzione
Utilizzando java.net.URL
URL baseUrl = new URL("http://www.google.com/someFolder/");
URL url = new URL(baseUrl, "../test.html");
Altri suggerimenti
Che ne dite di:
String s = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() + "/someImage.jpg";
Sembra che tu abbia già capito la parte difficile, ovvero su quale host stai utilizzando.Il resto è facile
String url = host + request.getContextPath() + "/someImage.jpg";
Dovrebbe darti ciò di cui hai bisogno.
questo codice funzionerà Linux, può basta combinare il percorso, se vuoi di più, il costruttore dell'URI potrebbe essere utile.
URL baseUrl = new URL("http://example.com/first");
URL targetUrl = new URL(baseUrl, Paths.get(baseUrl.getPath(), "second", "/third", "//fourth//", "fifth").toString());
se il tuo percorso contiene qualcosa che deve scappare, usa URLEncoder.encode
per sfuggirgli all'inizio.
URL baseUrl = new URL("http://example.com/first");
URL targetUrl = new URL(baseUrl, Paths.get(baseUrl.getPath(), URLEncoder.encode(relativePath, StandardCharsets.UTF_8), URLEncoder.encode(filename, StandardCharsets.UTF_8)).toString());
esempio:
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.file.Path;
import java.nio.file.Paths;
public class Main {
public static void main(String[] args) {
try {
URL baseUrl = new URL("http://example.com/first");
Path relativePath = Paths.get(baseUrl.getPath(), "second", "/third", "//fourth//", "fifth");
URL targetUrl = new URL(baseUrl, relativePath.toString());
System.out.println(targetUrl.toString());
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
}
produzione
http://example.com/first/second/third/fourth/fifth
baseUrl.getPath()
sono molto importanti, non dimenticatelo.
un esempio sbagliato:
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.file.Path;
import java.nio.file.Paths;
public class Main {
public static void main(String[] args) {
try {
URL baseUrl = new URL("http://example.com/first");
Path relativePath = Paths.get("second", "/third", "//fourth//", "fifth");
URL targetUrl = new URL(baseUrl, relativePath.toString());
System.out.println(targetUrl.toString());
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
}
produzione
http://example.com/second/third/fourth/fifth
abbiamo perso il nostro /first
nell'URL base.