package com.example.demo.util;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
/**
* @description: url转码
**/
public class UrlEncodeAndUrlDecode {
/** 字符编码. */
private static final String CHARSET = "UTF-8";
/**
* Url 编码
* @param s
* @return
*/
public static String encodeURIComponent(String s) {
String result = null;
try {
result = URLEncoder.encode(s, CHARSET)
.replaceAll("\\+", "%20")
.replaceAll("\\%21", "!")
.replaceAll("\\%27", "'")
.replaceAll("\\%28", "(")
.replaceAll("\\%29", ")")
.replaceAll("\\%7E", "~");
} catch (UnsupportedEncodingException e) {
result = s;
}
return result;
}
/**
* Url 解码
* @param s
* @return
*/
public static String decodeURIComponent(String s) {
if (s == null) {
return null;
}
String result = null;
try {
result = URLDecoder.decode(s, CHARSET);
} catch (UnsupportedEncodingException e) {
result = s;
}
return result;
}
public static void main(String[] args) {
System.out.println(encodeURIComponent("https://www.jianshu.com/p/cd70a69fbf3c"));
System.out.println(decodeURIComponent("https%3A%2F%2Fwww.jianshu.com%2Fp%2Fcd70a69fbf3c"));
}
}
运行结果:
https%3A%2F%2Fwww.jianshu.com%2Fp%2Fcd70a69fbf3c
https://www.jianshu.com/p/cd70a69fbf3c
本文介绍了一种使用Java实现的URL编码与解码方法,通过具体代码示例展示了如何进行URL的在线转码,包括对特殊字符的处理,适用于网络请求参数的编码解码场景。
1823

被折叠的 条评论
为什么被折叠?



