http转成https工具类
工具类代码如下:
点击查看代码
package com.astronaut.auction.modules.oss.utils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
/**
* @Classname HttpsUtil
* @Description: http转换https工具类
* @Date: 2022/8/9 0009 9:27
* @AUTHOR: 无泪之城
* @Version 1.0
*/
public class HttpsUtil {
private static final String HTTPS = "https://";
private static final String HTTP = "http://";
/**
* https 切换 (不包含scheme,http://)
* @param request
* @param url
* @return
*/
public static String httpsSwitch(HttpServletRequest request, String url, String httpsSwitch, String appServer){
if(StringUtils.isBlank(url)){
return url;
}
if ("0".equals(httpsSwitch)) {
return url;
}
String newUrl = "";
String host = request.getHeader("host");
if (StringUtils.isBlank(host)) {
host = appServer.replace("http://","");
}
host = host.replace(":80", "");
newUrl = HTTPS + host + request.getContextPath() + url;
return newUrl;
}
/**
* http转成https (包含scheme,http://),url含有端口不替换
* @param url
* @return
*/
public static String httpsSwitch(String url){
if(StringUtils.isBlank(url)){
return url;
}
String newUrl = "";
List<String> newUrlList = new ArrayList<>();
if (url.contains("http://")) {
replaceHttp(url, newUrl, newUrlList);
if (!CollectionUtils.isEmpty(newUrlList)) {
newUrl = newUrlList.get(0);
}
} else {
newUrl = url;
}
return newUrl;
}
/**
* 替换http
* @param url
* @param newUrl
* @param newUrlList
* @return
*/
private static void replaceHttp(String url, String newUrl, List<String> newUrlList) {
String scheme = "";
String context = "";
String[] array = url.split("://", 2);
if (array.length > 0) {
scheme = array[0];
context = array[1];
}
// 是否含有端口号
boolean containsPort = containsPort(context);
// 不含端口号才替换
if (!containsPort) {
scheme = scheme.replaceFirst("http", HTTPS);
} else {
scheme = HTTP;
}
newUrl = newUrl + scheme;
// 后面url是否含有://
boolean contains = context.contains("://");
if (contains) {
replaceHttp(context, newUrl, newUrlList);
} else {
newUrl = newUrl + context;
newUrlList.add(newUrl);
}
}
/**
* 是否含有端口号
* @param url
* @return
*/
private static boolean containsPort(String url) {
if (StringUtils.isNotBlank(url)) {
int firstIndex = url.indexOf("/");
if (firstIndex != -1) {
String remoteAddr = url.substring(0, firstIndex);
if (remoteAddr.contains(":")) {
return true;
}
} else {
if (url.contains(":")) {
return true;
}
}
}
return false;
}
}
本文来自博客园,作者:青喺半掩眉砂,转载请注明原文链接:https://www.cnblogs.com/xiaoguo-java/p/16564930.html
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)