zoukankan      html  css  js  c++  java
  • 通过调接口 下载文件流 的工具类

    舍弃公司特定的jar包,使用通用的工具类:

    第一个:

    package com..;
    
    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.OutputStream;
    import java.util.HashMap;
    import java.util.Map;
    import org.apache.http.Header;
    import org.apache.http.HeaderElement;
    import org.apache.http.HttpEntity;
    import org.apache.http.NameValuePair;
    import org.apache.http.client.config.RequestConfig;
    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.StringEntity;
    import org.apache.http.impl.client.CloseableHttpClient;
    import org.apache.http.impl.client.HttpClients;
    import org.apache.http.util.EntityUtils;
    import com.alibaba.fastjson.JSONObject;
    
    public class stuffLoad {
    
        public static void main(String[] args) throws IOException {
    
           
            Map<String ,Object> map = new HashMap<String ,Object>();
            map= getStuffInfo("http://.....",jsons);
            String fileName = (String) map.get("fileName");
            byte[] bytes = (byte[]) map.get("fileByte");
            //放在本地
            File file=new File("C:\Users\****\Desktop\"+fileName);
            OutputStream out = new FileOutputStream(file);
            out.write(bytes);
            out.close();
            
            //前台下载 方式
    //          try {
    //           response.setContentType(
    //          "application/octet-stream; charset=GBK");
    //           fileName = new String(fileName.getBytes(), "ISO8859-1");
    //           response.setHeader("Content-Disposition",
    //          "attachment; filename="" + fileName + """);
    //        OutputStream out = response.getOutputStream();
    //        if (bytes != null) {
    //         out.write(bytes);
    //        }
    //        out.close();
    //       } catch (Exception e) {
    //        e.printStackTrace();
    //       }
          }
            
    
    
        /** 
         * 发送Post请求  获取文件和名字
         * @param 
         * @return 
         */  
        private static Map<String ,Object> getStuffInfo(String url,JSONObject json) {  
            
             RequestConfig requestConfig = RequestConfig.custom()  
                     .setSocketTimeout(15000)  
                     .setConnectTimeout(15000)  
                     .setConnectionRequestTimeout(15000)  
                     .build();
            Map<String, Object> map = new HashMap<String, Object>();
            HttpPost httpPost = new HttpPost(url);
            httpPost.setHeader("Content-Type", "application/json");
            httpPost.setEntity(new StringEntity(json.toString(),
                    ContentType.create("application/json", "utf-8")));
            CloseableHttpClient httpClient = HttpClients.createDefault();  
            CloseableHttpResponse response = null;  
            HttpEntity entity = null;  
            byte[] responseContent = null;  
            try {  
                httpPost.setConfig(requestConfig);  
                // 执行请求   获取文件内容
                response = httpClient.execute(httpPost);  
                entity = response.getEntity(); 
                responseContent = EntityUtils.toByteArray(entity);
                map.put("fileByte", responseContent);
                // responseContent = EntityUtils.toString(entity, "UTF-8");  //如果需要返回字符串改这里就行了
                //获取文件名
                Header contentHeader = response
                        .getFirstHeader("Content-Disposition");
                      if (contentHeader != null) {
                       HeaderElement[] values = contentHeader.getElements();
                       if (values.length == 1) {
                        NameValuePair param = values[0]
                          .getParameterByName("filename");
                        if (param != null) {
                         String fileName = new String(param.getValue()
                           .toString().getBytes("ISO-8859-1"),
                           "GBK");
                        map.put("fileName", fileName);
                        }
                       }
                      }
            } catch (Exception e) {  
                e.printStackTrace();  
            } finally {  
                try {  
                    // 关闭连接,释放资源  
                    if (response != null) {  
                        response.close();  
                    }  
                    if (httpClient != null) {  
                        httpClient.close();  
                    }  
                } catch (IOException e) {  
                    e.printStackTrace();  
                }  
            }  
            return map;  
        } 
    }

    第二种写法:

    package com..
    
    import java.io.BufferedOutputStream;
    import java.io.ByteArrayOutputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.util.HashMap;
    import java.util.Map;
    import org.apache.http.Header;
    import org.apache.http.HeaderElement;
    import org.apache.http.HttpEntity;
    import org.apache.http.HttpResponse;
    import org.apache.http.NameValuePair;
    import org.apache.http.client.HttpClient;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.entity.StringEntity;
    import org.apache.http.impl.client.HttpClients;
    import org.apache.http.message.BasicHeader;
    import org.apache.http.protocol.HTTP;
    import com.alibaba.fastjson.JSONObject;
    
    
    public class HttpPostFJ {
        public static Map<String, Object> getStuffStream(String url,JSONObject jsonObject) {
            
              HttpClient httpClient = HttpClients.createDefault();
              Map<String, Object> map = new HashMap<String, Object>();
              try {
               // String encoderJson = URLEncoder.encode(json, HTTP.UTF_8);
               HttpPost method = new HttpPost(url);
               method.addHeader(HTTP.CONTENT_TYPE,
                 "application/json;charset=utf-8");
               StringEntity se = new StringEntity(jsonObject.toString(), "UTF-8");
               se.setContentType("text/json");
               se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
                 "application/json"));
               method.setEntity(se);
               HttpResponse httpResponse = httpClient.execute(method);
               BufferedOutputStream bos = null;
               FileOutputStream fos = null;
               InputStream is = null;
               try {
                System.out.println("httpClient状态:"+ httpResponse.getStatusLine().getStatusCode());
                // 连接成功
                if (200 == httpResponse.getStatusLine().getStatusCode()) {
                 HttpEntity httpEntity = httpResponse.getEntity();
                 is = httpEntity.getContent();
    //             map.put("byte", StreamHelper.toByteArray(is));
                 map.put("byte", toByteArray(is));
                 Header contentHeader = httpResponse
                   .getFirstHeader("Content-Disposition");
                 if (contentHeader != null) {
                  HeaderElement[] values = contentHeader.getElements();
                  if (values.length == 1) {
                   NameValuePair param = values[0]
                     .getParameterByName("filename");
                   if (param != null) {
                    String fileName = new String(param.getValue()
                      .toString().getBytes("ISO-8859-1"),
                      "GBK");
                    System.out.println("fileName----"+fileName );
                    map.put("fileName", fileName);
                   }
                  }
                 }
                 return map;
                }
               } catch (Exception e) {
                e.printStackTrace();
               } finally {
                if (bos != null) {
                 try {
                  bos.close();
                 } catch (IOException e1) {
                  e1.printStackTrace();
                 }
                }
                if (fos != null) {
                 try {
                  fos.close();
                 } catch (IOException e1) {
                  e1.printStackTrace();
                 }
                }
               }
              } catch (Exception e) {
                 System.out.println("接口访问失败!"+e);
                  }
                  return null;
                 }
        
        public static byte[] toByteArray(InputStream is) {
            if (is == null) {
                return null;
            } else {
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                toOutputStream(is, baos);
                return baos.toByteArray();
            }
        }
        
        public static void toOutputStream(InputStream is, OutputStream os) {
            byte[] buffer = new byte[2048];
            try {
                int bytesRead;
                while((bytesRead = is.read(buffer, 0, 1024)) != -1) {
                    os.write(buffer, 0, bytesRead);
                }
            } catch (IOException var5) {
              System.out.println("error:"+var5);
            }
        }
        
    }
  • 相关阅读:
    QT 读写sqllite数据库
    SQLLite 简介
    arcengine 开发经典帖 【强烈推荐仔细研读】
    IHookHelper的用法
    ArcSDE中Compress与Compact的区别
    以Network Dataset(网络数据集)方式实现的最短路径分析
    ArcGIS网络概述
    ClassLoader.getResourceAsStream(name);获取配置文件的方法
    Xml中SelectSingleNode方法,xpath查找某节点用法
    Spring整合JUnit4测试使用注解引入多个配置文件
  • 原文地址:https://www.cnblogs.com/lifan12589/p/13500918.html
Copyright © 2011-2022 走看看