HttpClient get请求获取数据流

HttpClient get请求获取数据流,将数据保存为文件

 1 public String getStreamFile(String url) throws Exception {
 2         HttpClient client = HttpClientUtils.createSSLInsecureClient();
 3         HttpGet get = new HttpGet(url);
 4         HttpResponse response = client.execute(get);
 5 //        获取消息头
 6 //        Header[] headers = response.getAllHeaders();
 7 //        for (Header header : headers) {
 8 //            System.out.println(MessageFormat.format("header:{0}={1}", header.getName(), header.getValue()));
 9 //        }
10         String fileName = response.getHeaders("Content-Disposition")[0].getValue().split("filename=")[1];
11         logger.info("文件名为" + fileName);
12 
13         if (response.getStatusLine().getStatusCode() == 200) {
14             //得到实体
15             HttpEntity entity = response.getEntity();
16             byte[] data = EntityUtils.toByteArray(entity);
17             //存入磁盘
18             FileOutputStream fos = new FileOutputStream(fileName);
19             fos.write(data);
20             fos.close();
21             logger.info("文件下载成功!");
22         } else {
23             throw new Exception("文件下载失败!Http状态码为" + response.getStatusLine().getStatusCode());
24         }
25         return fileName;
26     }

 

posted @ 2019-05-28 10:49  星瑞  阅读(9006)  评论(0编辑  收藏  举报