3.2.8 HttpClient文件下载

    技术2022-07-10  122

    下载HTML、图片、PDF和压缩等文件时,通常会采用两种方法。一种方法是,使用HttpEntity类将响应实体转换成字节数据,再利用输出流的方式写入到指定文件。另一种方法是使用HttpEntity类中的writeTo(OutputStream)方法,直接将响应实体写入指定的输出流中,这种方法简单且常用。如程序3-20所示,使用writeTo(OutputStream)方法下载"png"格式的图片文件。

    //程序3-20 public class HttpClientDownloadFile { public static void main(String[] args) throws Exception { String url = "https://www.leichuangkj.com/img/WechatIMG1.png"; //初始化httpClient HttpClient httpClient = HttpClients.custom().build(); HttpGet httpGet = new HttpGet(url); //获取结果 HttpResponse httpResponse = null; try { httpResponse = httpClient.execute(httpGet); } catch (IOException e) { e.printStackTrace(); } //非常简单的下载文件的方法 OutputStream out = new FileOutputStream("file/1.png"); httpResponse.getEntity().writeTo(out); EntityUtils.consume(httpResponse.getEntity()); //消耗实体 } }
    Processed: 0.010, SQL: 9