通过调接口 下载文件流 的工具类

舍弃公司特定的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);
        }
    }
    
}
原文地址:https://www.cnblogs.com/lifan12589/p/13500918.html