本文目录导读:

我来为您提供Java中URL编解码的完整案例。
基本URL编码和解码
import java.net.URLEncoder;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.io.UnsupportedEncodingException;
public class BasicUrlCodec {
public static void main(String[] args) throws UnsupportedEncodingException {
// 原始字符串
String original = "你好,世界! Hello World! 中文测试 & 特殊字符=100%";
// URL编码
String encoded = URLEncoder.encode(original, StandardCharsets.UTF_8.name());
System.out.println("编码后: " + encoded);
// URL解码
String decoded = URLDecoder.decode(encoded, StandardCharsets.UTF_8.name());
System.out.println("解码后: " + decoded);
// 验证是否一致
System.out.println("验证结果: " + original.equals(decoded));
}
}
完整工具类实现
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.LinkedHashMap;
import java.util.Map;
public class UrlUtil {
private static final String DEFAULT_CHARSET = StandardCharsets.UTF_8.name();
/**
* URL编码
*/
public static String encode(String value) {
return encode(value, DEFAULT_CHARSET);
}
/**
* URL编码(指定字符集)
*/
public static String encode(String value, String charset) {
if (value == null) return null;
try {
return URLEncoder.encode(value, charset);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("URL编码失败", e);
}
}
/**
* URL解码
*/
public static String decode(String value) {
return decode(value, DEFAULT_CHARSET);
}
/**
* URL解码(指定字符集)
*/
public static String decode(String value, String charset) {
if (value == null) return null;
try {
return URLDecoder.decode(value, charset);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("URL解码失败", e);
}
}
/**
* 生成带查询参数的URL
*/
public static String buildUrl(String baseUrl, Map<String, String> params) {
if (params == null || params.isEmpty()) {
return baseUrl;
}
StringBuilder sb = new StringBuilder(baseUrl);
sb.append(baseUrl.contains("?") ? "&" : "?");
boolean first = true;
for (Map.Entry<String, String> entry : params.entrySet()) {
if (!first) {
sb.append("&");
}
sb.append(encode(entry.getKey()))
.append("=")
.append(encode(entry.getValue()));
first = false;
}
return sb.toString();
}
/**
* 解析URL查询参数
*/
public static Map<String, String> parseQueryParams(String url) {
Map<String, String> params = new LinkedHashMap<>();
if (url == null || url.isEmpty()) return params;
String query = url.contains("?") ? url.substring(url.indexOf("?") + 1) : url;
if (query.isEmpty()) return params;
String[] pairs = query.split("&");
for (String pair : pairs) {
String[] keyValue = pair.split("=", 2);
if (keyValue.length == 2) {
params.put(decode(keyValue[0]), decode(keyValue[1]));
}
}
return params;
}
}
实用案例
import java.util.HashMap;
import java.util.Map;
public class UrlCodecExample {
public static void main(String[] args) {
// 案例1: 基础编解码
basicExample();
// 案例2: 构建带参数的URL
buildUrlExample();
// 案例3: 解析URL参数
parseUrlExample();
// 案例4: 不同场景编码
differentScenarioExample();
}
/**
* 基础编解码示例
*/
private static void basicExample() {
System.out.println("=== 基础编解码示例 ===");
String[] testStrings = {
"Hello World",
"你好世界",
"user@example.com/?name=张三&age=25",
"测试#特殊&字符=100%"
};
for (String str : testStrings) {
String encoded = UrlUtil.encode(str);
String decoded = UrlUtil.decode(encoded);
System.out.println("原始: " + str);
System.out.println("编码: " + encoded);
System.out.println("解码: " + decoded);
System.out.println("是否一致: " + str.equals(decoded));
System.out.println("-".repeat(50));
}
}
/**
* 构建URL示例
*/
private static void buildUrlExample() {
System.out.println("\n=== 构建带参数的URL ===");
Map<String, String> params = new HashMap<>();
params.put("keyword", "Java 编程");
params.put("page", "1");
params.put("size", "10");
params.put("sort", "创建时间");
String url = UrlUtil.buildUrl("https://example.com/api/search", params);
System.out.println("生成的URL: " + url);
// 解析回参数
Map<String, String> parsedParams = UrlUtil.parseQueryParams(url);
System.out.println("解析的参数: " + parsedParams);
}
/**
* 解析URL示例
*/
private static void parseUrlExample() {
System.out.println("\n=== 解析URL参数 ===");
String complexUrl = "https://example.com/path?city=北京&lat=39.90&lng=116.40&tags=科技%2C金融";
Map<String, String> params = UrlUtil.parseQueryParams(complexUrl);
System.out.println("完整URL: " + complexUrl);
System.out.println("解析结果:");
params.forEach((key, value) -> System.out.println(" " + key + " = " + value));
}
/**
* 不同场景编码
*/
private static void differentScenarioExample() {
System.out.println("\n=== 不同场景编码 ===");
// 1. 路径参数编码
String path = "产品目录/手机/新款手机";
String encodedPath = UrlUtil.encode(path);
System.out.println("路径编码: " + encodedPath);
// 2. 表单数据编码
String formData = "username=张三&password=abc123¬e=特殊字符:%&*";
String encodedForm = UrlUtil.encode(formData);
System.out.println("表单编码: " + encodedForm);
// 3. 文件下载URL
String fileName = "年度报告-2024.pdf";
String downloadUrl = "https://example.com/download?file=" + UrlUtil.encode(fileName);
System.out.println("下载URL: " + downloadUrl);
// 4. 多语言内容
String multilang = "こんにちは Καλημέρα Привет مرحبا";
String encodedMulti = UrlUtil.encode(multilang);
System.out.println("多语言编码: " + encodedMulti);
System.out.println("多语言解码: " + UrlUtil.decode(encodedMulti));
}
}
Spring Boot中的URL编解码
import org.springframework.web.util.UriComponentsBuilder;
import org.springframework.web.util.UriUtils;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
public class SpringUrlExample {
/**
* 使用UriComponentsBuilder构建URL
*/
public static void buildUrlWithSpring() {
Map<String, String> params = new HashMap<>();
params.put("keyword", "火锅 北京");
params.put("page", "1");
params.put("pageSize", "20");
URI uri = UriComponentsBuilder.fromUriString("https://api.example.com/search")
.queryParam("keyword", params.get("keyword"))
.queryParam("page", params.get("page"))
.queryParam("pageSize", params.get("pageSize"))
.build()
.toUri();
System.out.println("Spring构建URL: " + uri);
}
/**
* 使用UriUtils进行编解码
*/
public static void encodeDecodeWithSpring() {
String original = "Hello 你好 World!";
// 编码
String encoded = UriUtils.encode(original, StandardCharsets.UTF_8);
System.out.println("Spring编码: " + encoded);
// 解码
String decoded = UriUtils.decode(encoded, StandardCharsets.UTF_8);
System.out.println("Spring解码: " + decoded);
}
}
完整的测试代码
import java.util.Map;
public class Main {
public static void main(String[] args) {
System.out.println("========== URL编解码完整测试 ==========\n");
// 运行所有示例
UrlCodecExample.main(null);
// Spring示例
System.out.println("\n========== Spring工具测试 ==========");
SpringUrlExample.buildUrlWithSpring();
SpringUrlExample.encodeDecodeWithSpring();
// 边界测试
System.out.println("\n========== 边界测试 ==========");
testEdgeCases();
}
private static void testEdgeCases() {
// 空字符串
System.out.println("空字符串: '" + UrlUtil.encode("") + "'");
// null值
System.out.println("null值: " + UrlUtil.encode(null));
// 仅特殊字符
String special = "!@#$%^&*()";
System.out.println("特殊字符: " + special + " -> " + UrlUtil.encode(special));
// 长文本
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 1000; i++) {
sb.append("测试");
}
String longText = sb.toString();
String encodedLong = UrlUtil.encode(longText);
System.out.println("长文本长度: " + longText.length() + " -> 编码后长度: " + encodedLong.length());
}
}
重要注意事项
- 字符集一致性: 编码和解码必须使用相同的字符集,推荐使用UTF-8
- 空格处理: URLEncoder把空格编码为,URLDecoder把解码为空格
- 特殊字符: 某些字符在URL中有特殊含义,需要特别处理
- 性能考虑: 大量数据编解码时注意性能问题
- 安全性: 不要对已编码的URL再次编码,会导致双重编码问题
- 路径 vs 查询参数: 路径中的某些字符(如、)在路径和查询参数中的处理可能不同
这些示例覆盖了Java中URL编解码的常见场景,可以根据实际需求选择合适的实现方式。
版权声明:NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
足球直播
足球直播
足球直播
篮球直播
篮球直播
篮球直播
NBA直播
NBA直播
NBA直播
CBA直播
CBA直播
CBA直播
亚冠直播
亚冠直播
亚冠直播
欧冠直播
欧冠直播
欧冠直播
英超直播
英超直播
英超直播
西甲直播
西甲直播
西甲直播
中超直播
中超直播
中超直播
足球直播
足球直播
足球直播
篮球直播
篮球直播
篮球直播
NBA直播
NBA直播
NBA直播
CBA直播
CBA直播
CBA直播
亚冠直播
亚冠直播
亚冠直播
欧冠直播
欧冠直播
欧冠直播
英超直播
英超直播
英超直播
西甲直播
西甲直播
西甲直播
中超直播
中超直播
中超直播
足球直播
足球直播
足球直播
篮球直播
篮球直播
篮球直播
NBA直播
NBA直播
NBA直播
CBA直播
CBA直播
CBA直播
亚冠直播
亚冠直播
亚冠直播
欧冠直播
欧冠直播
欧冠直播
英超直播
英超直播
英超直播
西甲直播
西甲直播
西甲直播
中超直播
中超直播
中超直播
足球直播
足球直播
足球直播
篮球直播
篮球直播
篮球直播
NBA直播
NBA直播
NBA直播
CBA直播
CBA直播
CBA直播
亚冠直播
亚冠直播
亚冠直播
欧冠直播
欧冠直播
欧冠直播
英超直播
英超直播
英超直播
西甲直播
西甲直播
西甲直播
中超直播
中超直播
中超直播
曼联直播
曼联直播
曼联直播
日职联直播
日职联直播
日职联直播
澳超直播
澳超直播
澳超直播
阿森纳直播
阿森纳直播
阿森纳直播
足球直播
足球直播
足球直播
NBA直播
NBA直播
NBA直播
曼联直播
曼联直播
曼联直播
日职联直播
日职联直播
日职联直播
澳超直播
澳超直播
澳超直播
阿森纳直播
阿森纳直播
阿森纳直播
足球直播
足球直播
足球直播
NBA直播
NBA直播
NBA直播
曼联直播
曼联直播
曼联直播
日职联直播
日职联直播
日职联直播
澳超直播
澳超直播
澳超直播
阿森纳直播
阿森纳直播
阿森纳直播
足球直播
足球直播
足球直播
NBA直播
NBA直播
NBA直播
曼联直播
曼联直播
曼联直播
日职联直播
日职联直播
日职联直播
澳超直播
澳超直播
澳超直播
阿森纳直播
阿森纳直播
阿森纳直播
足球直播
足球直播
足球直播
NBA直播
NBA直播
NBA直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
足球直播
足球直播
足球直播
足球直播
足球直播
英超直播
英超直播
英超直播
英超直播
英超直播
篮球直播
篮球直播
篮球直播
篮球直播
篮球直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
中超直播
中超直播
中超直播
中超直播
中超直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
足球直播
足球直播
足球直播
足球直播
足球直播
英超直播
英超直播
英超直播
英超直播
英超直播
篮球直播
篮球直播
篮球直播
篮球直播
篮球直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
中超直播
中超直播
中超直播
中超直播
中超直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播