mirror of
https://github.com/danieldemus/openhab-addons
synced 2026-07-29 12:34:21 +02:00
[http] Replace deprecated URL constructor (#19519)
* Fix unicode Signed-off-by: Leo Siepel <leosiepel@gmail.com> Signed-off-by: lsiepel <leosiepel@gmail.com> Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
This commit is contained in:
+32
-4
@@ -16,7 +16,6 @@ import java.net.IDN;
|
||||
import java.net.MalformedURLException;
|
||||
import java.net.URI;
|
||||
import java.net.URISyntaxException;
|
||||
import java.net.URL;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
@@ -63,12 +62,41 @@ public class Util {
|
||||
* @throws URISyntaxException if parameter could not be converted to a URI
|
||||
*/
|
||||
public static URI uriFromString(String s) throws MalformedURLException, URISyntaxException {
|
||||
URL url = new URL(s);
|
||||
URI uri = new URI(url.getProtocol(), url.getUserInfo(), IDN.toASCII(url.getHost()), url.getPort(),
|
||||
url.getPath(), url.getQuery(), url.getRef());
|
||||
URI uri = parse(s);
|
||||
return URI.create(uri.toASCIIString().replace("+", "%2B").replace("%25%25", "%"));
|
||||
}
|
||||
|
||||
private static final Pattern URL_PATTERN = Pattern.compile("^(?:(?<scheme>[a-zA-Z][a-zA-Z0-9+.-]*):)?//"
|
||||
+ "(?:(?<userinfo>[^@/?#]*)@)?" + "(?<host>(?:\\[[a-fA-F0-9:]+\\])|(?:[^:/?#]*))(?::(?<port>\\d+))?"
|
||||
+ "(?<path>/[^?#]*)?" + "(?:\\?(?<query>[^#]*))?" + "(?:#(?<fragment>.*))?");
|
||||
|
||||
/**
|
||||
* Parses a URL string and returns a {@link URI} object, converting Unicode hostnames to ASCII as needed.
|
||||
*
|
||||
* @param url the URL string to parse
|
||||
* @return a {@link URI} representing the parsed URL
|
||||
* @throws URISyntaxException if the input string is not a valid URL
|
||||
*/
|
||||
public static URI parse(String url) throws URISyntaxException {
|
||||
Matcher m = URL_PATTERN.matcher(url.trim());
|
||||
if (!m.matches()) {
|
||||
throw new URISyntaxException(url,
|
||||
"Invalid URL. Expected format: [scheme]://[host][:port][path][?query][#fragment]. Input: '" + url
|
||||
+ "'");
|
||||
}
|
||||
|
||||
String host = m.group("host");
|
||||
if (host != null) {
|
||||
host = IDN.toASCII(host); // <-- convert Unicode to ASCII
|
||||
}
|
||||
|
||||
String portStr = m.group("port");
|
||||
int port = (portStr != null && !portStr.isEmpty()) ? Integer.parseInt(portStr) : -1;
|
||||
|
||||
return new URI(m.group("scheme"), m.group("userinfo"), host, port, m.group("path"), m.group("query"),
|
||||
m.group("fragment"));
|
||||
}
|
||||
|
||||
/**
|
||||
* Format a string using {@link String#format(String, Object...)} but allow non-format percent characters
|
||||
*
|
||||
|
||||
Reference in New Issue
Block a user