http文件下载服务端(SpringMVC框架)
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
@Controller
public class DownloadFileController {
@RequestMapping("downloadFile")
public void mark(HttpServletRequest request, HttpServletResponse response) throws IOException {
//需要返回的文件路径
String filePath = "";
String pwd = request.getParameter("PASSWORD");
String user = request.getParameter("USER");
if ("test".equals(user)&&"test".equals(pwd)){
ZipOutputStream zos = null;
try {
//设置返回的请求头
response.setContentType("multipart/form-data");
//获取要打包的多个文件
File filepath = new File(filePath);
String[] tempList = filepath.list();
if(null != tempList){
OutputStream out = response.getOutputStream();
zos = new ZipOutputStream(out);
if (tempList.length>1){
for (String fileNamePath : tempList) {
File file = new File(filepath+"\\"+fileNamePath);
ZipEntry entry = new ZipEntry(file.getName());
zos.putNextEntry(entry);
byte [] bytes = new byte[1024];
int len;
FileInputStream in = new FileInputStream(file);
while((len = in.read(bytes)) != -1) {
zos.write(bytes, 0, len);
}
}
}else{
File file = new File(tempList[0]);
ZipEntry entry = new ZipEntry(file.getName());
zos.putNextEntry(entry);
byte [] bytes = new byte[1024];
int len;
FileInputStream in = new FileInputStream(file);
while((len = in.read(bytes)) != -1) {
zos.write(bytes, 0, len);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}else{
response.setContentType("text/html;charset=UTF-8");
response.getWriter().write("{'serviceFlag':'0','MSG':'警告:用户名与密码不正确!!!'}");
}
}
}
http请求客户端
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import org.junit.Test;
import java.io.*;
import java.util.HashMap;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import static org.apache.http.Consts.UTF_8;
public class TestDownload {
private static Logger logger = Logger.getLogger(TestDownload.class);
public static final String TYPE_NAME_JSON = "application/json";
public static final String TYPE_NAME_TEXT = "text/plain";
private static JSONObject jsonStr;
@Test
public void test_DownloadFile(){
multipartRequestForMark_01("http://www.forward.ink/MusicUpload01/testdownloadfile.do?user=admin&password=admin");
}
public static void multipartRequestForMark_01(String url){
HttpPost httpPost = new HttpPost(url);
MultipartEntityBuilder builder = MultipartEntityBuilder.create().setCharset(UTF_8);
HttpEntity multipart = builder.build();
HttpClient httpclient = new DefaultHttpClient();
httpPost.setEntity(multipart);
Map<String, Object> map = new HashMap<String, Object>();
try {
CloseableHttpResponse httpResponse = (CloseableHttpResponse) httpclient.execute(httpPost);
try {
int statusCode = httpResponse.getStatusLine().getStatusCode();
if(statusCode == HttpStatus.SC_OK) {
HttpEntity entity = httpResponse.getEntity();//从response里获取数据实体
String str = String.valueOf(entity.getContentType());
str = str.substring(str.indexOf(":") + 1, str.indexOf(";")).replace(" ", "");
if (TYPE_NAME_JSON.equals(str)) {
HttpEntity resEntity = httpResponse.getEntity();
if(entity !=null){
Map<String, Object> JSONMap = toJson(EntityUtils.toString(entity));
if(JSONMap !=null && JSONMap.size()>0){
String serviceFlag = (String) JSONMap.get("serviceFlag");
String msg = (String) JSONMap.get("msg");
logger.info("返回的数据为:--------" + msg);
}
}
System.out.println(EntityUtils.toString(resEntity));//httpclient自带的工具类读取返回数据
System.out.println(resEntity.getContent());
EntityUtils.consume(resEntity);
}else{
InputStream in = entity.getContent();//获取数据流
ZipInputStream zin = new ZipInputStream(in);//封装成zip输入流
BufferedOutputStream bos = null;
ZipEntry ze;
//文件存放地址
String path = "E:\\test\\";
File file = null;
try {
while((ze = zin.getNextEntry()) != null) {
logger.info("文件的名字为:"+ze.getName());
file = new File(path + ze.getName());
FileOutputStream fos = new FileOutputStream(file);
int len;
byte [] bytes = new byte[2048];
bos = new BufferedOutputStream(fos,2048);
while((len = zin.read(bytes, 0, 2048)) != -1) {
bos.write(bytes, 0, len);
}
}
bos.flush();
bos.close();
zin.close();
} catch (Exception e) {
logger.error("异常 " + e);
}
}
}
}catch (Exception e){
logger.error(e);
}finally {
if (httpResponse != null) httpResponse.close();
}
} catch (Exception e) {
logger.error( e);
}
}
public static Map<String,Object> toJson(String jsonArray){
Map<String,Object> map = new HashMap<String, Object>();
try {
logger.info("开始解析返回的数据------");
jsonStr = JSONObject.parseObject(jsonArray);
String serviceFlag = (String) jsonStr.get("serviceFlag");
String msg = (String) jsonStr.get("msg");
map.put("serviceFlag",serviceFlag);
map.put("msg",msg);
}catch (Exception e){
logger.info("解析JSON出错,数据结构不对");
} finally {
logger.info("返回的JSON为:"+jsonStr);
logger.info("JSON数据解析完成---------");
}
return map;
}
}
文件上传地址:
https://blog.csdn.net/qq_39304415/article/details/85156615
阿里云新老客户专属低价&高额代金券新用户低至1折云服务器低至89元年
https://www.aliyun.com/minisite/goods?userCode=b84d0jpg