zoukankan      html  css  js  c++  java
  • (十一)文件的上传和下载

    父类:

    package com.automation.util.httpclient;
    
    import com.alibaba.fastjson.JSON;
    import com.alibaba.fastjson.JSONObject;
    import com.alibaba.fastjson.parser.Feature;
    import com.automation.pojo.HttpClientResult;
    import org.apache.http.HttpStatus;
    import org.apache.http.NameValuePair;
    import org.apache.http.client.CookieStore;
    import org.apache.http.client.entity.UrlEncodedFormEntity;
    import org.apache.http.client.methods.CloseableHttpResponse;
    import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
    import org.apache.http.client.methods.HttpRequestBase;
    import org.apache.http.cookie.Cookie;
    import org.apache.http.entity.StringEntity;
    import org.apache.http.impl.client.CloseableHttpClient;
    import org.apache.http.message.BasicNameValuePair;
    import org.apache.http.util.EntityUtils;
    
    import java.io.IOException;
    import java.io.UnsupportedEncodingException;
    import java.util.ArrayList;
    import java.util.List;
    import java.util.Map;
    import java.util.Set;
    
    public class HttpClientUtil {
    
        // 编码格式。发送编码格式统一用UTF-8
        protected static final String ENCODING = "UTF-8";
    
        // 设置连接超时时间,单位毫秒。
        protected static final int CONNECT_TIMEOUT = 6000;
    
        // 请求获取数据的超时时间(即响应时间),单位毫秒。
        protected static final int SOCKET_TIMEOUT = 6000;
    
        /**
         * Description: 封装请求头
         * @param params
         * @param httpMethod
         */
        public static void packageHeader(Map<String, String> params, HttpRequestBase httpMethod) {
            // 封装请求头
            if (params != null) {
                Set<Map.Entry<String, String>> entrySet = params.entrySet();
                for (Map.Entry<String, String> entry : entrySet) {
                    // 设置到请求头到HttpRequestBase对象中
                    httpMethod.setHeader(entry.getKey(), entry.getValue());
                }
            }
        }
    
        /**
         * Description: 封装请求参数
         *
         * @param params
         * @param httpMethod
         * @throws UnsupportedEncodingException
         */
        public static void packageParam(Map<String, String> params, HttpEntityEnclosingRequestBase httpMethod)
                throws UnsupportedEncodingException {
            // 封装请求参数
            if (params != null) {
                List<NameValuePair> nvps = new ArrayList<NameValuePair>();
                Set<Map.Entry<String, String>> entrySet = params.entrySet();
                for (Map.Entry<String, String> entry : entrySet) {
                    nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
                }
    
                // 设置到请求的http对象中
                httpMethod.setEntity(new UrlEncodedFormEntity(nvps, ENCODING));
            }
        }
    
        /**
         * Description: 封装json请求参数
         *
         * @param params
         * @param httpMethod
         * @throws UnsupportedEncodingException
         */
        public static void packageJsonParam(Map<String, String> params, HttpEntityEnclosingRequestBase httpMethod)
                throws UnsupportedEncodingException {
            // 封装请求参数
            if (params != null) {
                JSONObject jsonParam = new JSONObject();
                Set<Map.Entry<String,String>> entrySet = params.entrySet();
                for(Map.Entry<String,String> entry : entrySet){
                    jsonParam.put(entry.getKey(),entry.getValue());
                }
                StringEntity entity = new StringEntity(jsonParam.toString(),ENCODING);
                entity.setContentEncoding(ENCODING);
                entity.setContentType("application/json");
                // 设置到请求的http对象中
                httpMethod.setEntity(entity);
            }
        }
    
        /**
         * Description: 获得响应结果
         *
         * @param httpResponse
         * @param httpClient
         * @param httpMethod
         * @return
         * @throws Exception
         */
        public static JSONObject getResponse(CloseableHttpResponse httpResponse,
                                             CloseableHttpClient httpClient, HttpRequestBase httpMethod) throws Exception {
            // 执行请求
            httpResponse = httpClient.execute(httpMethod);
    
            // 获取返回结果
            if (httpResponse != null && httpResponse.getStatusLine() != null) {
                StringBuffer content = new StringBuffer();
                if (httpResponse.getEntity() != null) {
                    content.append(EntityUtils.toString(httpResponse.getEntity(), ENCODING));
                }
                return JSON.parseObject(content.toString(), Feature.OrderedField);
            }
            JSONObject data = new JSONObject();
            data.put("code","999");
            data.put("content","网络异常");
            return data;
        }
    
        /**
         * Description: 获得响应结果
         *
         * @param httpResponse
         * @param httpClient
         * @param httpMethod
         * @return
         * @throws Exception
         */
        public static HttpClientResult getHttpClientResult(CloseableHttpResponse httpResponse,
                                                           CloseableHttpClient httpClient, HttpRequestBase httpMethod) throws Exception {
            // 执行请求
            httpResponse = httpClient.execute(httpMethod);
    
            // 获取返回结果
            if (httpResponse != null && httpResponse.getStatusLine() != null) {
                String content = "";
                if (httpResponse.getEntity() != null) {
                    content = EntityUtils.toString(httpResponse.getEntity(), ENCODING);
                }
                return new HttpClientResult(httpResponse.getStatusLine().getStatusCode(), content);
            }
            return new HttpClientResult(HttpStatus.SC_INTERNAL_SERVER_ERROR);
        }
    
        /**
         * Description: 获得响应结果
         *
         * @param httpResponse
         * @param httpClient
         * @param httpMethod
         * @return
         * @throws Exception
         */
        public static JSONObject getResponseCookie(CloseableHttpResponse httpResponse,
                                                   CloseableHttpClient httpClient, HttpRequestBase httpMethod, CookieStore store) throws Exception {
            // 执行请求
            httpResponse = httpClient.execute(httpMethod);
    
            JSONObject CookieAndToken = new JSONObject();
    
            // 获取返回结果
            if (httpResponse != null && httpResponse.getStatusLine() != null) {
                StringBuffer content = new StringBuffer();
                if (httpResponse.getEntity() != null) {
                    content.append(EntityUtils.toString(httpResponse.getEntity(), ENCODING));
                }
    
                List<Cookie> CookieList =  store.getCookies();
                String tmpCookie = "";
                for (Cookie cookie:CookieList){
                    tmpCookie += cookie.getName() +"="+cookie.getValue()+";";
                }
                JSONObject data = JSON.parseObject(content.toString(), Feature.OrderedField).getJSONObject("data");
    
                String token = data.getString("token");
    
                CookieAndToken.put("token",token);
                CookieAndToken.put("cookie",tmpCookie.substring(0,tmpCookie.length()-1));
    
                return CookieAndToken;
            }
            JSONObject data = new JSONObject();
            data.put("code","999");
            data.put("content","网络异常");
            return data;
        }
    
    
        /**
         * Description: 释放资源
         *
         * @param httpResponse
         * @param httpClient
         * @throws IOException
         */
        public static void release(CloseableHttpResponse httpResponse, CloseableHttpClient httpClient) throws IOException {
            // 释放资源
            if (httpResponse != null) {
                httpResponse.close();
            }
            if (httpClient != null) {
                httpClient.close();
            }
        }
    
    }
    

    HttpClientFileUtil

    package com.automation.util.httpclient;
    
    import com.alibaba.fastjson.JSONObject;
    import com.automation.util.FileUtil;
    import org.apache.http.*;
    import org.apache.http.client.HttpClient;
    import org.apache.http.client.config.RequestConfig;
    import org.apache.http.client.methods.CloseableHttpResponse;
    import org.apache.http.client.methods.HttpGet;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.entity.mime.MultipartEntityBuilder;
    import org.apache.http.entity.mime.content.ContentBody;
    import org.apache.http.impl.client.CloseableHttpClient;
    import org.apache.http.impl.client.HttpClients;
    
    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.InputStream;
    import java.util.Map;
    
    public class HttpClientFileUtil extends HttpClientUtil{
        private static final int cache = 10 * 1024;
        //上传文件
        public static JSONObject postFileMultiPart(String url, Map<String, ContentBody> reqParam) throws Exception {
            CloseableHttpClient httpClient = HttpClients.createDefault();
            // 创建httpget.
            HttpPost httpPost = new HttpPost(url);
    
            //setConnectTimeout:设置连接超时时间,单位毫秒。setConnectionRequestTimeout:设置从connect Manager获取Connection 超时时间,单位毫秒。这个属性是新加的属性,因为目前版本是可以共享连接池的。setSocketTimeout:请求获取数据的超时时间,单位毫秒。 如果访问一个接口,多少时间内无法返回数据,就直接放弃此次调用。
            RequestConfig defaultRequestConfig = RequestConfig.custom().setConnectTimeout(5000).setConnectionRequestTimeout(5000).setSocketTimeout(15000).build();
            httpPost.setConfig(defaultRequestConfig);
    
            MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
            for(Map.Entry<String,ContentBody> param : reqParam.entrySet()){
                multipartEntityBuilder.addPart(param.getKey(), param.getValue());
            }
            HttpEntity reqEntity = multipartEntityBuilder.build();
            httpPost.setEntity(reqEntity);
            CloseableHttpResponse httpResponse = null;
            try{
                return getResponse(httpResponse,httpClient,httpPost);
            }finally {
                release(httpResponse,httpClient);
            }
        }
    
        //下载文件
        /**
         * 获取response header中Content-Disposition中的filename值
         *
         * @param
         * @return
         */
        public static int downloadFileByGet(String url, String filepath, Map<String, String> headers,String fileName){
            int StatusCode = 0;
            try {
                HttpClient client = HttpClients.createDefault();
                HttpGet httpget = new HttpGet(url);
                httpget.setConfig(RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT).setSocketTimeout(SOCKET_TIMEOUT).build());
                //封装请求头
                packageHeader(headers,httpget);
    
                HttpResponse response = client.execute(httpget);
                StatusCode = response.getStatusLine().getStatusCode();
                HttpEntity entity = response.getEntity();
                InputStream is = entity.getContent();
    
                if (fileName == null){
                    fileName = getFileName(response);
                }
    
                if (filepath == null){
                    filepath = FileUtil.getResourcesPath("excel"+FileUtil.getSplash()+"download"+FileUtil.getSplash()+fileName);
                }
    
                File file = new File(filepath);
                file.getParentFile().mkdirs();
                FileOutputStream fileout = new FileOutputStream(file);
                /**
                 * 根据实际运行效果 设置缓冲区大小
                 */
                byte[] buffer = new byte[cache];
                int ch = 0;
                while ((ch = is.read(buffer)) != -1) {
                    fileout.write(buffer, 0, ch);
                }
                is.close();
                fileout.flush();
                fileout.close();
    
            } catch (Exception e) {
                e.printStackTrace();
            }
            return StatusCode;
        }
    
        public static String getFileName(HttpResponse response) {
            Header contentHeader = response.getFirstHeader("Content-Disposition");
            String filename = null;
            if (contentHeader != null) {
                HeaderElement[] values = contentHeader.getElements();
                if (values.length == 1) {
                    NameValuePair param = values[0].getParameterByName("filename");
                    if (param != null) {
                        try {
                            filename = param.getValue();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
            return filename;
        }
    }
    

      

      

  • 相关阅读:
    ECMAScript 6 基础入门
    软件历史版本存档及下载
    arduino 编程基础
    生活中的实验 —— 家庭电路
    电子元件 —— 继电器
    电与磁 —— 电磁铁
    windows cmd 命令行 —— 进程与服务
    计算机硬件、摄影设备、物质、材料英语
    DHCP服务器备份、还原、迁移
    SVN同步
  • 原文地址:https://www.cnblogs.com/lvchengda/p/13036423.html
Copyright © 2011-2022 走看看