发送http请求,获取返回的zip包并读取包内的文件

需要引入jar包:httpclient、httpmime、httpcore、javax.servlet-api。 

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class ReturnFile {


    //接收http请求并将需要的文件打包返回
    public void mark(HttpServletResponse response) {
        OutputStream out = null;
        ZipOutputStream zos = null;
        try {
            response.setContentType("multipart/form-data");
            //获取要打包的多个文件
            File file1 = new File("C:/Users/xhc/Desktop/a/spring-quartz.xml");
            File file2 = new File("C:/Users/xhc/Desktop/a/spring-servlet.xml");
            List fileList = new ArrayList<>();
            fileList.add(file1);
            fileList.add(file2);
            out = response.getOutputStream();
            zos = new ZipOutputStream(out);
            for (File file : fileList) {
                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);
                }
                zos.closeEntry();
                in.close();
            }

        } catch (Exception e) {

        }finally {
            if(zos != null) {
                try {
                    zos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(out != null) {
                try {
                    zos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;

import java.io.*;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

public class HttpClientUtils {

	private static final Charset UTF_8 = Charset.forName("UTF-8");

	/**
	 * 获取httpclient
	 */
	private static CloseableHttpClient httpclient = getHttpClient();

	/**
	 * 创建HttpClient
	 */
	private static CloseableHttpClient getHttpClient() {

		PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
		cm.setMaxTotal(20);
		cm.setDefaultMaxPerRoute(10);

		return HttpClients.custom().setConnectionManager(cm).evictExpiredConnections()
				.evictIdleConnections(5L, TimeUnit.SECONDS).build();

	}

	/**
	 * 服务器返回状态码200时才正常
	 */
	private static void assertStatus(HttpResponse res) throws IOException {
		int statusCode = res.getStatusLine().getStatusCode();
		if (statusCode == HttpStatus.SC_OK) {
			System.out.println("响应正常");
		} else {
			throw new IOException("服务器响应状态异常,状态码:" + statusCode);
		}
	}



	public static Map multipartRequestForMark(String url, Map params, String[] filePath,
			String[] fileName) {
		HttpPost httpPost = new HttpPost(url);
		MultipartEntityBuilder builder = MultipartEntityBuilder.create().setCharset(UTF_8);
		String value ;
		if (params != null) {
			for (String key : params.keySet()) {
				value = params.get(key);
				if (value == null)
					value = "";
				builder.addTextBody(key, value, ContentType.APPLICATION_JSON);
			}
		}

		if ((filePath != null) && (fileName != null) && (filePath.length == fileName.length)) {
			for (int i = 0; i < filePath.length; ++i) {
				builder.addBinaryBody("file" + i, new File(filePath[i]), ContentType.APPLICATION_OCTET_STREAM,
						fileName[i]);
			}
		}
		HttpEntity multipart = builder.build();
		httpPost.setEntity(multipart);
		Map map = new HashMap<>();
		try {

			CloseableHttpResponse response = httpclient.execute(httpPost);
			try {
				assertStatus(response);
				HttpEntity entity = response.getEntity();
				InputStream in = entity.getContent();
				Charset c = Charset.forName("UTF-8");
				ZipInputStream zin = new ZipInputStream(in, c);
				BufferedOutputStream bos;
				ZipEntry ze;
				File file;
				List listFile = new ArrayList<>();
				try {
					while ((ze = zin.getNextEntry()) != null) {
						file = getXmlImageFile(getXrayImageDir_xml(), ze.getName());
						listFile.add(file);
						FileOutputStream fos = new FileOutputStream(file);
						int len;
						byte[] bytes = new byte[1024 * 2];
						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) {
				}
				map.put("status", true);
				map.put("result", listFile);
				return map;
			} finally {
				if (response != null)
					response.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		map.put("status", false);
		return map;
	}

	/**
	 * 获取xml文件的文件夹路径
	 */
	private static String getXrayImageDir_xml() {
		String path = "D:/xml/";
		File dir = new File(path);
		if (!dir.exists())
			dir.mkdirs();
		return dir.getAbsolutePath();
	}

	/**
	 * 取得xml文件
	 */
	private static File getXmlImageFile(String dir, String fileName) {
		File xrayFile = new File(dir, fileName);
		if (!xrayFile.exists())
			try {
				xrayFile.createNewFile();
			} catch (IOException e) {
				e.printStackTrace();
			}
		return xrayFile;
	}

}

 

 

 

你可能感兴趣的:(zip压缩)