zoukankan      html  css  js  c++  java
  • 使用httpclient下载远程文件

    有些时候我们需要使用httclient直接从网络获取一个文件
    httpclient底层获取文件的方式仍然是封装的流,但是使用起来会比较方便,可以设置代理等web设施
    示例代码如下

    CloseableHttpClient client = HttpClients.createDefault();
    RequestConfig config = null;
    //使用代理
    
    if(null != proxy && StringUtils.isNotBlank(proxy.ip) && proxy.port > 0){
        HttpHost proxy = new HttpHost(proxy.ip, proxy.port);  
        config = RequestConfig.custom().setProxy(proxy).build(); 
    }else{
    //没有代理,使用默认值
        config = RequestConfig.custom().build();
    }
    //目标文件url
    HttpGet httpGet = new HttpGet(url);
    httpGet.setConfig(config);
    //下载需登陆,设置登陆后的cookie
    httpGet.addHeader("Cookie", cookie);
    
    try {
        HttpResponse respone = client.execute(httpGet);
        if(respone.getStatusLine().getStatusCode() != HttpStatus.SC_OK){
            return ;
        }
        HttpEntity entity = respone.getEntity();
        if(entity != null) {
            InputStream is = entity.getContent();
            File file = new File("目标文件生成路径");
            FileOutputStream fos = new FileOutputStream(file); 
            byte[] buffer = new byte[4096];
            int len = -1;
            while((len = is.read(buffer) )!= -1){
                fos.write(buffer, 0, len);
            }
            fos.close();
            is.close();
            files.add(file);
        }
    } catch (Exception e) {
        
    }finally{
        try {
            client.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
  • 相关阅读:
    office的高级应用
    python基础
    maven 资源导出失败问题
    单向环形链表和约瑟夫问题
    JDBC连接MySQL
    环形队列
    稀疏数组
    数据库锁机制和事务隔离级别总结
    context的简单应用
    JDBC基本使用方法
  • 原文地址:https://www.cnblogs.com/swbzmx/p/5604360.html
Copyright © 2011-2022 走看看