下载方法 支持重定向

下载方法 支持重定向 

Signed-off-by: 高雄 <admin@cxcp.com>
This commit is contained in:
高雄 2023-07-28 06:36:23 +00:00 committed by Gitee
parent 3da330341f
commit 75fe682433
No known key found for this signature in database
GPG Key ID: 173E9B9CA92EEF8F
1 changed files with 48 additions and 0 deletions

View File

@ -12,7 +12,10 @@ import org.springframework.util.StringUtils;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.util.UUID;
import static cn.keking.utils.KkFileUtils.isFtpUrl;
@ -37,6 +40,7 @@ public class DownloadUtils {
public static ReturnResponse<String> downLoad(FileAttribute fileAttribute, String fileName) {
// 忽略ssl证书
String urlStr = null;
HttpURLConnection urlcon;
try {
SslUtils.ignoreSsl();
urlStr = fileAttribute.getUrl().replaceAll("\\+", "%20");
@ -70,6 +74,50 @@ public class DownloadUtils {
}
try {
URL url = WebUtils.normalizedURL(urlStr);
if (!urlStr.toLowerCase().startsWith("ftp:")&& !urlStr.toLowerCase().startsWith("file")){
urlcon=(HttpURLConnection)url.openConnection();
urlcon.setConnectTimeout(30000);
urlcon.setReadTimeout(30000);
urlcon.setInstanceFollowRedirects(false);
int responseCode = urlcon.getResponseCode();
if(responseCode != 200){
if (responseCode == HttpURLConnection.HTTP_MOVED_PERM || responseCode == HttpURLConnection.HTTP_MOVED_TEMP) { //301 302
url =new URL(urlcon.getHeaderField("Location"));
}
if (responseCode == 403|| responseCode == 500) { //301 302
response.setCode(1);
response.setContent(null);
response.setMsg("下载失败:地址错误!" + urlStr);
return response;
}
if (responseCode == 404 ) { //404
try {
urlStr = URLDecoder.decode(urlStr, "UTF-8");
urlStr = URLDecoder.decode(urlStr, "UTF-8");
url = WebUtils.normalizedURL(urlStr);
urlcon=(HttpURLConnection)url.openConnection();
urlcon.setConnectTimeout(30000);
urlcon.setReadTimeout(30000);
urlcon.setInstanceFollowRedirects(false);
responseCode = urlcon.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_MOVED_PERM || responseCode == HttpURLConnection.HTTP_MOVED_TEMP) { //301 302
url =new URL(urlcon.getHeaderField("Location"));
}
if(responseCode == 404 ||responseCode == 403|| responseCode == 500 ){
response.setCode(1);
response.setContent(null);
response.setMsg("下载失败:地址错误!" + urlStr);
return response;
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}finally {
assert urlcon != null;
urlcon.disconnect();
}
}
}
}
if (!fileAttribute.getSkipDownLoad()) {
if (isHttpUrl(url)) {
File realFile = new File(realPath);