使用HttpClients提供的http请求获取流,然后将流写入文件

需要使用的依赖 ->httpclient-4.5版本

  
                org.apache.httpcomponents
                httpclient
                4.5
 
  • 工作中遇到文件上传至亚马逊后,返回一个url(https://zihebest.s3.ap-southeast-1.amazonaws.com/20190423142511?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Date=20190423T062525Z&X-Amz-SignedHeaders=host&X-Amz-Expires=86400&X-Amz-Credential=AKIA5YQILDFXAKCE5LYV%2F20190423%2Fap-southeast-1%2Fs3%2Faws4_request&X-Amz-Signature=5ff7917702439363cbe39930f250f8eb2ff89337387953f52a0a62720ea10d9a),在浏览器中键入该地址后可直接下载,但文件是未知文件,无文件后缀名,由此可推测该url真实是一个流
            CloseableHttpClient httpclient = HttpClients.createDefault();
            HttpGet httpGet = new HttpGet(result.getData());
            HttpResponse backResponse = httpclient.execute(httpGet);
            response.reset();
            response.setContentType("application/msexcel");// 定义输出类型
            response.setCharacterEncoding("UTF-8");
            out = response.getOutputStream();
            backResponse.getEntity().writeTo(out);

代码如上:需要借助HttpServletResponse 对象将流直接与浏览器建立下载链接,result.getData()=https://zihebest.s3.ap-southeast-1.amazonaws.com/20190423142511?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Date=20190423T062525Z&X-Amz-SignedHeaders=host&X-Amz-Expires=86400&X-Amz-Credential=AKIA5YQILDFXAKCE5LYV%2F20190423%2Fap-southeast-1%2Fs3%2Faws4_request&X-Amz-Signature=5ff7917702439363cbe39930f250f8eb2ff89337387953f52a0a62720ea10d9a

你可能感兴趣的:(使用HttpClients提供的http请求获取流,然后将流写入文件)