?Java?,????java.net.URLEncoder
???URL?????????,????????:
- ??try-with-resources??:?Java 7??,????try-with-resources????????,???????????
import java.net.URLEncoder; import java.nio.charset.StandardCharsets; public class URLEncoderExample { public static void main(String[] args) { String url = "https://example.com?param1=value1¶m2=value2"; try { String encodedUrl = encodeURL(url); System.out.println("Encoded URL: " + encodedUrl); } catch (Exception e) { e.printStackTrace(); } } public static String encodeURL(String url) throws Exception { return URLEncoder.encode(url, StandardCharsets.UTF_8.toString()) .replaceAll("\\+", " ") // ??"+"??? .replaceAll("!", "!") // ??"!"???? .replaceAll("'", "'") // ??"'"???? .replaceAll("(", "(") // ??"("???? .replaceAll(")", ")") // ??")"???? .replaceAll("~", "~"); // ??"~"???? } }
- ??Apache Commons Lang?:Apache Commons Lang????????
URLEncoderUtils
????,????URL????????,??????????????????Maven,???pom.xml?????????:
org.apache.commons commons-lang3 3.12.0
??,????URLEncoderUtils.encode
????URL??:
import org.apache.commons.lang3.text.URLEncoderUtils; import java.nio.charset.StandardCharsets; public class URLEncoderExample { public static void main(String[] args) { String url = "https://example.com?param1=value1¶m2=value2"; try { String encodedUrl = encodeURL(url); System.out.println("Encoded URL: " + encodedUrl); } catch (Exception e) { e.printStackTrace(); } } public static String encodeURL(String url) throws Exception { return URLEncoderUtils.encode(url, StandardCharsets.UTF_8.toString()); } }
??????????URL????????try-with-resources?????????????,?Apache Commons Lang????????????????????????????????????