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