您的位置:首页 > 理论基础 > 计算机网络

SpringMVC下http和https路径下的文件下载

2016-11-23 10:01 369 查看
package com.example;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.UUID;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/file/")
public class Test {

/**
* @MethodName downloadFile
* @Description 下载文件
*
* @param request
* @param response
* @throws IOException
*/
@RequestMapping("downloadFile")
public void downloadFile(HttpServletRequest request, HttpServletResponse response) throws IOException {
String fileUrl = request.getParameter("fileUrl");
if (null == fileUrl || fileUrl.trim().length() == 0 || !fileUrl.startsWith("http")) {
return;
}

String fileName = request.getParameter("fileName");
if (null == fileName || fileName.trim().length() == 0) {
fileName = UUID.randomUUID().toString() + "." + getExtensionName(fileUrl);
}

BufferedOutputStream bf = null;
try {
response.setHeader("Content-disposition", "attachment; filename = " + fileName);

bf = new BufferedOutputStream(response.getOutputStream());

if (fileUrl.startsWith("http://")) {
bf.write(this.httpConverBytes(fileUrl));
} else if (fileUrl.startsWith("https://")) {
bf.write(this.httpsConverBytes(fileUrl));
}

} catch (Exception e) {
e.printStackTrace();
}
finally {
if (bf != null) {
bf.close();
bf.flush();
}
}
}

/**
* @MethodName httpConverBytes
* @Description http路径文件内容获取
*
* @param path
* @return
*/
public byte[] httpConverBytes(String path) {
BufferedInputStream in = null;
ByteArrayOutputStream out = null;
URLConnection conn = null;

try {
URL url = new URL(path);
conn = url.openConnection();

in = new BufferedInputStream(conn.getInputStream());

out = new ByteArrayOutputStream(1024);
byte[] temp = new byte[1024];
int size = 0;
while ((size = in.read(temp)) != -1) {
out.write(temp, 0, size);
}
byte[] content = out.toByteArray();
return content;
} catch (Exception e) {
e.printStackTrace();
}
finally {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}

/**
* @MethodName httpsConverBytes
* @Description https路径文件内容获取
*
* @param url
* @return
*/
private byte[] httpsConverBytes(String url) {
BufferedInputStream inStream = null;
ByteArrayOutputStream outStream = null;

try {

TrustManager[] tm = { new TrustAnyTrustManager() };
SSLContext sc = SSLContext.getInstance("SSL", "SunJSSE");
sc.init(null, tm, new java.security.SecureRandom());
URL console = new URL(url);

HttpsURLConnection conn = (HttpsURLConnection) console.openConnection();
conn.setSSLSocketFactory(sc.getSocketFactory());
conn.setHostnameVerifier(new TrustAnyHostnameVerifier());
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestMethod("POST");
conn.connect();

inStream = new BufferedInputStream(conn.getInputStream());
outStream = new ByteArrayOutputStream();

byte[] buffer = new byte[1024];
int len = 0;
while ((len = inStream.read(buffer)) != -1) {
outStream.write(buffer, 0, len);
}

byte[] content = outStream.toByteArray();
return content;

} catch (Exception e) {
e.printStackTrace();
}
finally {
if (null != inStream) {
try {
inStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}

if (null != outStream) {
try {
outStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

return null;
}

private static class TrustAnyTrustManager implements X509TrustManager {
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {}

public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {}

public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[] {};
}
}

private static class TrustAnyHostnameVerifier implements HostnameVerifier {
public boolean verify(String hostname, SSLSession session) {
return true;
}
}

public static String getExtensionName(String filename) {
if (filename != null && filename.length() > 0) {
int dot = filename.lastIndexOf('.');
if (dot > -1 && dot < filename.length() - 1) {
return filename.substring(dot + 1);
}
}
return filename;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐