下面列出了怎么用java.net.URLDecoder的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* 获得指定Cookie的值
* @param request 请求对象
* @param response 响应对象
* @param name 名字
* @param isRemove 是否移除
* @return 值
*/
public static String getCookie(HttpServletRequest request, HttpServletResponse response, String name, String path, boolean isRemove) {
String value = null;
if (StringUtils.isNotBlank(name)){
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (Cookie cookie : cookies) {
if (cookie.getName().equals(name)) {
try {
value = URLDecoder.decode(cookie.getValue(), "utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
if (isRemove && response != null) {
cookie.setPath(path);
cookie.setMaxAge(0);
response.addCookie(cookie);
}
}
}
}
}
return value;
}
private void parseParams(String queryString, CommandRequest request) {
for (String parameter : queryString.split("&")) {
if (StringUtil.isBlank(parameter)) {
continue;
}
String[] keyValue = parameter.split("=");
if (keyValue.length != 2) {
continue;
}
String value = StringUtil.trim(keyValue[1]);
try {
value = URLDecoder.decode(value, SentinelConfig.charset());
} catch (UnsupportedEncodingException e) {
}
request.addParam(StringUtil.trim(keyValue[0]), value);
}
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest request = ((HttpServletRequest) servletRequest);
Map<String, String> formatMap = new HashMap<>(16);
// 获取自定义参数
Set<String> expandFormat = traceLogProperties.getFormat();
for (String k : expandFormat) {
String v = request.getHeader(k);
if (!StringUtils.isEmpty(v)) {
formatMap.put(k, URLDecoder.decode(v, "UTF-8"));
}
}
// 写入 MDC
TraceContentFactory.storageMDC(formatMap);
filterChain.doFilter(servletRequest, servletResponse);
MDC.clear();
}
@Override
public CommandResponse<String> handle(CommandRequest request) {
String data = request.getParam("data");
if (StringUtil.isBlank(data)) {
return CommandResponse.ofFailure(new IllegalArgumentException("empty data"));
}
try {
data = URLDecoder.decode(data, "utf-8");
RecordLog.info("[ModifyClusterClientConfigHandler] Receiving cluster client config: " + data);
ClusterClientStateEntity entity = JSON.parseObject(data, ClusterClientStateEntity.class);
ClusterClientConfigManager.applyNewConfig(entity.toClientConfig());
ClusterClientConfigManager.applyNewAssignConfig(entity.toAssignConfig());
return CommandResponse.ofSuccess(CommandConstants.MSG_SUCCESS);
} catch (Exception e) {
RecordLog.warn("[ModifyClusterClientConfigHandler] Decode client cluster config error", e);
return CommandResponse.ofFailure(e, "decode client cluster config error");
}
}
/**
* 得到Cookie的值,
*
* @param request
* @param cookieName
* @return
*/
public static String getCookieValue(HttpServletRequest request, String cookieName, boolean isDecoder) {
Cookie[] cookieList = request.getCookies();
if (cookieList == null || cookieName == null) {
return null;
}
String retValue = null;
try {
for (int i = 0; i < cookieList.length; i++) {
if (cookieList[i].getName().equals(cookieName)) {
if (isDecoder) {
retValue = URLDecoder.decode(cookieList[i].getValue(), "UTF-8");
} else {
retValue = cookieList[i].getValue();
}
break;
}
}
} catch (UnsupportedEncodingException e) {
logger.error("Cookie Decode Error.", e);
}
return retValue;
}
@Override
public CommandResponse<String> handle(CommandRequest request) {
String data = request.getParam("data");
if (StringUtil.isBlank(data)) {
return CommandResponse.ofFailure(new IllegalArgumentException("Bad data"));
}
try {
data = URLDecoder.decode(data, "utf-8");
} catch (Exception e) {
RecordLog.info("Decode gateway rule data error", e);
return CommandResponse.ofFailure(e, "decode gateway rule data error");
}
RecordLog.info(String.format("[API Server] Receiving rule change (type: gateway rule): %s", data));
String result = SUCCESS_MSG;
List<GatewayFlowRule> flowRules = JSONArray.parseArray(data, GatewayFlowRule.class);
GatewayRuleManager.loadRules(new HashSet<>(flowRules));
return CommandResponse.ofSuccess(result);
}
private RpcProvider convert2Provider(String serviceName, String providerData) {
try {
providerData = URLDecoder.decode(providerData, "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
RpcProvider rpcProvider = new RpcProvider();
ProviderInfo providerInfo = ProviderHelper.toProviderInfo(providerData);
rpcProvider.setServiceName(serviceName);
rpcProvider.setAddress(providerInfo.getHost());
rpcProvider.setPort(providerInfo.getPort());
String appName = providerInfo.getStaticAttr(ProviderInfoAttrs.ATTR_APP_NAME);
rpcProvider.setAppName(appName);
rpcProvider.setWeight(providerInfo.getWeight());
return rpcProvider;
}
public static Set<Class<?>> scan(String packageName, boolean recursive) {
String packageDirName = packageName.replace('.', '/');
try {
Set<Class<?>> classSet = new LinkedHashSet<>();
Enumeration<URL> dirs = Thread.currentThread().getContextClassLoader().getResources(packageDirName);
while (dirs.hasMoreElements()) {
URL url = dirs.nextElement();
String protocol = url.getProtocol();
// If it's file, storage on the server
if ("file".equals(protocol)) {
String filePath = URLDecoder.decode(url.getFile(), "UTF-8");
classSet.addAll(findClassesInPackageByFile(packageName, filePath, recursive));
} else if ("jar".equals(protocol)) {
classSet.addAll(findClassesInPackageByJar(packageName, url, recursive));
}
}
return classSet;
} catch (IOException e) {
logger.error("error happen while scanning package", e);
}
return Collections.emptySet();
}
private ImageSource(@NonNull Uri uri) {
// #114 If file doesn't exist, attempt to url decode the URI and try again
String uriString = uri.toString();
if (uriString.startsWith(FILE_SCHEME)) {
File uriFile = new File(uriString.substring(FILE_SCHEME.length() - 1));
if (!uriFile.exists()) {
try {
uri = Uri.parse(URLDecoder.decode(uriString, "UTF-8"));
} catch (UnsupportedEncodingException e) {
// Fallback to encoded URI. This exception is not expected.
}
}
}
this.bitmap = null;
this.uri = uri;
this.resource = null;
this.tile = true;
}
/**
* 高级查询
* @param queryWrapper
* @param parameterMap
*/
public static void doSuperQuery(QueryWrapper<?> queryWrapper,Map<String, String[]> parameterMap) {
if(parameterMap!=null&& parameterMap.containsKey(SUPER_QUERY_PARAMS)){
String superQueryParams = parameterMap.get(SUPER_QUERY_PARAMS)[0];
// 解码
try {
superQueryParams = URLDecoder.decode(superQueryParams, "UTF-8");
} catch (UnsupportedEncodingException e) {
log.error("--高级查询参数转码失败!", e);
}
List<QueryCondition> conditions = JSON.parseArray(superQueryParams, QueryCondition.class);
log.info("---高级查询参数-->"+conditions.toString());
for (QueryCondition rule : conditions) {
if(oConvertUtils.isNotEmpty(rule.getField()) && oConvertUtils.isNotEmpty(rule.getRule()) && oConvertUtils.isNotEmpty(rule.getVal())){
addEasyQuery(queryWrapper, rule.getField(), QueryRuleEnum.getByValue(rule.getRule()), rule.getVal());
}
}
}
}
/**
* 导出excel
*
* @param request
* @param response
*/
@RequestMapping(value = "/exportXls")
public ModelAndView exportXls(HttpServletRequest request, HttpServletResponse response) {
// Step.1 组装查询条件
QueryWrapper<JoaDemo> queryWrapper = null;
try {
String paramsStr = request.getParameter("paramsStr");
if (oConvertUtils.isNotEmpty(paramsStr)) {
String deString = URLDecoder.decode(paramsStr, "UTF-8");
JoaDemo joaDemo = JSON.parseObject(deString, JoaDemo.class);
queryWrapper = QueryGenerator.initQueryWrapper(joaDemo, request.getParameterMap());
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
//Step.2 AutoPoi 导出Excel
ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
List<JoaDemo> pageList = joaDemoService.list(queryWrapper);
//导出文件名称
mv.addObject(NormalExcelConstants.FILE_NAME, "流程测试列表");
mv.addObject(NormalExcelConstants.CLASS, JoaDemo.class);
mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("流程测试列表数据", "导出人:Jeecg", "导出信息"));
mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
return mv;
}
/**
* 得到Cookie的值,
*
* @param request
* @param cookieName
* @return
*/
public static String getCookieValue(HttpServletRequest request, String cookieName, boolean isDecoder) {
Cookie[] cookieList = request.getCookies();
if (cookieList == null || cookieName == null) {
return null;
}
String retValue = null;
try {
for (int i = 0; i < cookieList.length; i++) {
if (cookieList[i].getName().equals(cookieName)) {
if (isDecoder) {
retValue = URLDecoder.decode(cookieList[i].getValue(), "UTF-8");
} else {
retValue = cookieList[i].getValue();
}
break;
}
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return retValue;
}
protected <T> void verifyExporterUrlGeneration(T config, Object[][] dataTable) {
// 1. fill corresponding config with data
////////////////////////////////////////////////////////////
fillConfigs(config, dataTable, TESTVALUE1);
// 2. export service and get url parameter string from db
////////////////////////////////////////////////////////////
servConf.export();
String paramStringFromDb = getProviderParamString();
try {
paramStringFromDb = URLDecoder.decode(paramStringFromDb, "UTF-8");
} catch (UnsupportedEncodingException e) {
// impossible
}
assertUrlStringWithLocalTable(paramStringFromDb, dataTable, config.getClass().getName(), TESTVALUE1);
// 4. unexport service
////////////////////////////////////////////////////////////
servConf.unexport();
}
/**
* Check whether the given path contains invalid escape sequences.
* @param path the path to validate
* @return {@code true} if the path is invalid, {@code false} otherwise
*/
private boolean isInvalidEncodedPath(String path) {
if (path.contains("%")) {
try {
// Use URLDecoder (vs UriUtils) to preserve potentially decoded UTF-8 chars
String decodedPath = URLDecoder.decode(path, "UTF-8");
if (isInvalidPath(decodedPath)) {
return true;
}
decodedPath = processPath(decodedPath);
if (isInvalidPath(decodedPath)) {
return true;
}
}
catch (IllegalArgumentException | UnsupportedEncodingException ex) {
// Should never happen...
}
}
return false;
}
/**
* Check whether the given path contains invalid escape sequences.
* @param path the path to validate
* @return {@code true} if the path is invalid, {@code false} otherwise
*/
private boolean isInvalidEncodedPath(String path) {
if (path.contains("%")) {
try {
// Use URLDecoder (vs UriUtils) to preserve potentially decoded UTF-8 chars
String decodedPath = URLDecoder.decode(path, "UTF-8");
if (isInvalidPath(decodedPath)) {
return true;
}
decodedPath = processPath(decodedPath);
if (isInvalidPath(decodedPath)) {
return true;
}
}
catch (IllegalArgumentException | UnsupportedEncodingException ex) {
// Should never happen...
}
}
return false;
}
private boolean isInvalidEncodedPath(String resourcePath) {
if (resourcePath.contains("%")) {
// Use URLDecoder (vs UriUtils) to preserve potentially decoded UTF-8 chars...
try {
String decodedPath = URLDecoder.decode(resourcePath, "UTF-8");
if (decodedPath.contains("../") || decodedPath.contains("..\\")) {
logger.warn("Resolved resource path contains encoded \"../\" or \"..\\\": " + resourcePath);
return true;
}
}
catch (UnsupportedEncodingException ex) {
// Should never happen...
}
}
return false;
}
/**
* 高级查询
* @param queryWrapper
* @param parameterMap
*/
public static void doSuperQuery(QueryWrapper<?> queryWrapper,Map<String, String[]> parameterMap) {
if(parameterMap!=null&& parameterMap.containsKey(SUPER_QUERY_PARAMS)){
String superQueryParams = parameterMap.get(SUPER_QUERY_PARAMS)[0];
// 解码
try {
superQueryParams = URLDecoder.decode(superQueryParams, "UTF-8");
} catch (UnsupportedEncodingException e) {
log.error("--高级查询参数转码失败!", e);
}
List<QueryCondition> conditions = JSON.parseArray(superQueryParams, QueryCondition.class);
log.info("---高级查询参数-->"+conditions.toString());
for (QueryCondition rule : conditions) {
if(oConvertUtils.isNotEmpty(rule.getField()) && oConvertUtils.isNotEmpty(rule.getRule()) && oConvertUtils.isNotEmpty(rule.getVal())){
addEasyQuery(queryWrapper, rule.getField(), QueryRuleEnum.getByValue(rule.getRule()), rule.getVal());
}
}
}
}
@Test
public void testBatchJobIdEnDecryption() throws Exception {
String jobId = "100";
SecretKeySpec secretKey = BulkDataConfigUtil.getBatchJobIdEncryptionKey("test-key");
assertNotNull(secretKey);
String encryptedJobId = BulkDataExportUtil.encryptBatchJobId(jobId, secretKey);
assertNotNull(encryptedJobId);
assertFalse(encryptedJobId.equals(jobId));
encryptedJobId = URLDecoder.decode(encryptedJobId, StandardCharsets.UTF_8.toString());
assertNotNull(encryptedJobId);
String decryptedJobId = BulkDataExportUtil.decryptBatchJobId(encryptedJobId, secretKey);
assertNotNull(decryptedJobId);
assertEquals(decryptedJobId, jobId);
}
/**
* Returns the time-stamp for a document's last update
*/
private final long getLastModified(String uri) {
try {
URL url = new URL(uri);
URLConnection connection = url.openConnection();
long timestamp = connection.getLastModified();
// Check for a "file:" URI (courtesy of Brian Ewins)
if (timestamp == 0){ // get 0 for local URI
if ("file".equals(url.getProtocol())){
File localfile = new File(URLDecoder.decode(url.getFile()));
timestamp = localfile.lastModified();
}
}
return(timestamp);
}
// Brutal handling of all exceptions
catch (Exception e) {
return(System.currentTimeMillis());
}
}
@Override
public DataHandler getAttachmentAsDataHandler(String contentId) {
if (contentId.startsWith(CID)) {
contentId = contentId.substring(CID.length());
try {
contentId = URLDecoder.decode(contentId, "UTF-8");
}
catch (UnsupportedEncodingException ex) {
// ignore
}
contentId = '<' + contentId + '>';
}
DataHandler dataHandler = this.mimeContainer.getAttachment(contentId);
if (dataHandler == null) {
throw new IllegalArgumentException("No attachment found for " + contentId);
}
return dataHandler;
}
@Override
public CommandResponse<String> handle(CommandRequest request) {
String data = request.getParam("data");
if (StringUtil.isBlank(data)) {
return CommandResponse.ofFailure(new IllegalArgumentException("empty data"));
}
try {
data = URLDecoder.decode(data, "utf-8");
RecordLog.info("[ModifyServerNamespaceSetHandler] Receiving cluster server namespace set: " + data);
Set<String> set = JSON.parseObject(data, new TypeReference<Set<String>>() {});
ClusterServerConfigManager.loadServerNamespaceSet(set);
return CommandResponse.ofSuccess("success");
} catch (Exception e) {
RecordLog.warn("[ModifyServerNamespaceSetHandler] Decode cluster server namespace set error", e);
return CommandResponse.ofFailure(e, "decode client cluster config error");
}
}
private RpcConsumer convert2Consumer(String serviceName, String providerData) {
try {
providerData = URLDecoder.decode(providerData, "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
RpcConsumer rpcConsumer = new RpcConsumer();
ProviderInfo consumerInfo = ProviderHelper.toProviderInfo(providerData);
String appName = consumerInfo.getStaticAttr(ProviderInfoAttrs.ATTR_APP_NAME);
rpcConsumer.setAppName(appName);
rpcConsumer.setServiceName(serviceName);
rpcConsumer.setAddress(consumerInfo.getHost());
rpcConsumer.setPort(consumerInfo.getPort());
return rpcConsumer;
}
public static List<LinkProperty> getLinkExtensions(String urlEncodedExtensionString) {
List<LinkProperty> resultList = new ArrayList<>();
if (StringUtils.isNotBlank(urlEncodedExtensionString)) {
if (urlEncodedExtensionString.startsWith("?")) {
urlEncodedExtensionString = urlEncodedExtensionString.substring(1);
}
for (String keyValueParamString : urlEncodedExtensionString.split("&")) {
String[] parts = keyValueParamString.split("=");
if (StringUtils.isNotBlank(parts[0])) {
try {
if (parts.length > 1 && StringUtils.isNotBlank(parts[1])) {
resultList.add(new LinkProperty(PropertyType.LinkExtension, URLDecoder.decode(parts[0], "UTF-8"), URLDecoder.decode(parts[1], "UTF-8")));
} else {
resultList.add(new LinkProperty(PropertyType.LinkExtension, URLDecoder.decode(parts[0], "UTF-8"), ""));
}
} catch (UnsupportedEncodingException e) {
logger.error("Error occured: " + e.getMessage(), e);
}
}
}
}
return resultList;
}
@Override
public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory binderFactory) throws Exception {
RequestJsonToPo parameterAnnotation = parameter.getParameterAnnotation(RequestJsonToPo.class);
Objects.requireNonNull(parameterAnnotation);
String value = parameterAnnotation.value();
Class<?> clazz = parameter.getNestedParameterType();
String jsonParameter = nativeWebRequest.getParameter(value);
if (jsonParameter == null) {
if (clazz.isAssignableFrom(List.class)) {
return Lists.newArrayList();
}
return clazz.newInstance();
}
jsonParameter = URLDecoder.decode(jsonParameter, StandardCharsets.UTF_8.name());
if (clazz.isAssignableFrom(List.class) || clazz.isAssignableFrom(ArrayList.class)) {
String typeName = ((sun.reflect.generics.reflectiveObjects.ParameterizedTypeImpl) parameter.getGenericParameterType()).getActualTypeArguments()[0].getTypeName();
Class<?> aClass = Class.forName(typeName);
return JsonUtil.toList(jsonParameter, aClass);
} else {
return JsonUtil.toObject(jsonParameter, clazz);
}
}
@SuppressWarnings("deprecation")
public static String decode(String url) {
if (isUTF8(url)) {
url = UTF8Decode(url);
} else {
url = URLDecoder.decode(url);
}
return url;
}
public static String escapeUrl(RestRequestContainer request, Templater templater)
throws MalformedURLException, URISyntaxException {
String finalUrl = templater.replaceTags(request.getUrl());
URL url = new URL(URLDecoder.decode(finalUrl));
URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(), url.getQuery(), url.getRef());
return uri.toASCIIString();
}
public static String decodeURL(String encodedData) throws Exception {
try {
return URLDecoder.decode(encodedData, "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new Exception("Invalid url-encoded data");
}
}
/**
* scan the package.
*
* @param basePackage the basic class package's string.
* @param recursive whether to search recursive.
* @return Set of the found classes.
*/
public Set<Class<?>> getPackageAllClasses(String basePackage, boolean recursive) {
if (basePackage == null) {
return new HashSet<>();
}
Set<Class<?>> classes = new LinkedHashSet<Class<?>>();
String packageName = basePackage;
if (packageName.endsWith(".")) {
packageName = packageName.substring(0, packageName.lastIndexOf('.'));
}
String package2Path = packageName.replace('.', '/');
try {
Enumeration<URL> dirs = Thread.currentThread().getContextClassLoader().getResources(package2Path);
while (dirs.hasMoreElements()) {
URL url = dirs.nextElement();
String protocol = url.getProtocol();
if ("file".equals(protocol)) {
String filePath = URLDecoder.decode(url.getFile(), "UTF-8");
doScanPackageClassesByFile(classes, packageName, filePath, recursive);
} else if ("jar".equals(protocol)) {
doScanPackageClassesByJar(packageName, url, recursive, classes);
}
}
} catch (IOException e) {
LOGGER.error("ignore this IOException", e);
}
TreeSet<Class<?>> sortedClasses = new TreeSet<>(new ClassNameComparator());
sortedClasses.addAll(classes);
return sortedClasses;
}
/**
* 解码字符串
* @param text 字符串
* @return
*/
public static String decodeURL(String text){
try {
return URLDecoder.decode(text, CommonConfig.UNIFY_CHARSET);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
}
/**
* 获取文件外链
* @param bucketName
* @param objectName
* @param expires
* @return
*/
public static String getObjectURL(String bucketName, String objectName, Date expires) {
initOSS(endPoint, accessKeyId, accessKeySecret);
try{
if(ossClient.doesObjectExist(bucketName,objectName)){
URL url = ossClient.generatePresignedUrl(bucketName,objectName,expires);
return URLDecoder.decode(url.toString(),"UTF-8");
}
}catch (Exception e){
log.info("文件路径获取失败" + e.getMessage());
}
return null;
}