http文件下载服务端(SpringMVC框架)
import org.spring work.stereotype.Controller;
import org.spring work.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.JSON ;
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 JSON 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, > map = new HashMap<String, >();
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, > 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, > toJson(String jsonArray){
Map<String, > map = new HashMap<String, >();
try {
logger.info(\"开始解析返回的数据------\");
jsonStr = JSON .parse (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
继续阅读与本文标签相同的文章
上一篇 :
阿里云共建无锡鸿山飞凤平台一期亮相物联网博览会
下一篇 :
软件测试的目的和原则
-
数据库基础技术实践#网络安全基础技术实践课程
2026-05-18栏目: 教程
-
MySQL每组求最值的记录与每组前N条记录
2026-05-18栏目: 教程
-
OCP-052考试题库汇总(55)-CUUG内部解答版
2026-05-18栏目: 教程
-
【云栖活动】架构师、产品经理一对一座谈会/WORKSHOP-已截止
2026-05-18栏目: 教程
-
MySQL入门书籍和方法分享
2026-05-18栏目: 教程
