package com.tofly.xrtygis.custom.util;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClients;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;

/**
 * @author FlashWJL
 * @date 2021/7/7 17:13
 */
public class RecordAPIUtil {

    /**
     * 根据URL获取文件
     *
     * @param recordURL       远程获取（下载）文件地址
     * @param servletResponse
     */
    public static void getFileByURL(String recordURL, HttpServletResponse servletResponse) {
        //创建HttpCkient对象
        HttpClient client = HttpClients.createDefault();
        // 要调用的接口方法
        String url = recordURL;
//        //建立HttpPost对象
//        HttpPost post = new HttpPost(url);
        //创建HttpGET对象
        HttpGet get = new HttpGet(url);
        try {
            //调用HttpClient对象的execute发送请求；执行提交
            HttpResponse res = client.execute(get);
            //如果执行后返回成功
            if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                //设置音频响应
                servletResponse.setHeader("Content-Type", "audio/mpeg");
                servletResponse.setHeader("Content-type", "text/html; charset=UTF-8");
                servletResponse.setContentType("application/x-download");
                servletResponse.setContentType("text/html;charset=UTF-8");//解决乱码
                //这是文件名称
                servletResponse.setHeader("Content-Disposition", "attachment;filename=" + res.getFirstHeader("Content-Disposition").getValue());
                //响应输出流
                OutputStream out = servletResponse.getOutputStream();
                //获取执行请求后的响应体
                HttpEntity responseEntity = res.getEntity();
                //获取执行请求后的输入流
                InputStream inputStream = responseEntity.getContent();
                //文件名
//                System.out.println(res.getFirstHeader("Content-Disposition").getValue());
                byte[] buf = new byte[1024];
                int count = 0;
                while ((count = inputStream.read(buf)) > 0) {
                    //写入
                    out.write(buf, 0, count);
                }
                //刷新响应
                servletResponse.flushBuffer();
                //刷新输出流和关闭流
                out.flush();
                out.close();
            }
        } catch (Exception e) {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            e.printStackTrace(new PrintStream(baos));
        }

    }


}
