用HttpClient下载img

来源:互联网 发布:mysql unique查询 编辑:程序博客网 时间:2024/05/19 21:43

这是我再一个项目中用到的一段代码:

    //picUrl 图片连接,name 图片名称,imgPath 图片要保存的地址    public void downloadImg(String picUrl ,String name ,String imgPath) throws ClientProtocolException, IOException{    CloseableHttpClient httpclient = HttpClients.createDefault();    try{        HttpGet get = new HttpGet(picUrl);          HttpResponse response = httpclient.execute(get);        HttpEntity entity = response.getEntity();          InputStream in = entity.getContent();          String dir = imgPath;        File file = new File(dir,name+".jpg");          try {            FileOutputStream fout = new FileOutputStream(file);            int l = -1;            byte[] tmp = new byte[1024];            while ((l = in.read(tmp)) != -1) {                fout.write(tmp, 0, l);            }            fout.flush();            fout.close();        } finally {            // 关闭低层流。            in.close();        }    }catch(Exception e1){        System.out.println("下载图片出错"+picUrl);    }    httpclient.close();}

另附HttpClient的使用详解

http://blog.csdn.net/wangpeng047/article/details/19624529

0 0
原创粉丝点击