httpclient模拟浏览器下载文件-常用方法集锦

本文介绍了如何在Java中利用httpclient库下载文件。分别展示了使用Java自带API和commons-httpclient库的方法,包括相关配置、示例代码及参考资料。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

需求 :下载资源文件到本地


public void getDownloadResource(String url, String filePath) throws IOException {

        File file = new File(filePath);

        if (!file.exists()) {
            file.createNewFile();
        }

        try {
            OutputStream out = new FileOutputStream(file);

            // Method1
            downLoadByJdk(url, out);
            // method2
            // downLoadByHttpCommons(url, out);
            // method3
            downloadByCommonsHttpclient(url, out);

        } catch (Exception e) {

        }
    }

Java自带的API实现

public static void downLoadByJdk(String url, OutputStream out) {
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            IOUtils.copy(conn.getInputStream(), out);
            out.close();
        } catch (Exception e) {
            System.out.println("发送 POST 请求出现异常!"+e);
            e.printStackTrace();
        }
    }

httpClient

  • pom
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.2</version>
</dependency>
  • demo
 public static void downLoadByHttpClient(String url, OutputStream out) throws IOException {

        //创建httpclient实例,采用默认的参数配置
        CloseableHttpClient httpClient = HttpClients.createDefault();

        HttpGet get = new HttpGet(url);   //使用Get方法提交

        //请求的参数配置,分别设置连接池获取连接的超时时间,连接上服务器的时间,服务器返回数据的时间
        RequestConfig config = RequestConfig.custom()
                .setConnectionRequestTimeout(3000)
                .setConnectTimeout(3000)
                .setSocketTimeout(3000)
                .build();
        //配置信息添加到Get请求中
        get.setConfig(config);
        //通过httpclient的execute提交 请求 ,并用CloseableHttpResponse接受返回信息
        CloseableHttpResponse response = httpClient.execute(get);
        //服务器返回的状态
        int statusCode = response.getStatusLine().getStatusCode();
        //判断返回的状态码是否是200200 代表服务器响应成功,并成功返回信息
        if (statusCode == HttpStatus.SC_OK) {
            //EntityUtils 获取返回的信息。官方不建议使用使用此类来处理信息
//            System.out.println("Demo.example -------->" + EntityUtils.toString(response.getEntity() , Consts.UTF_8));
            IOUtils.copy(response.getEntity().getContent(), out);
            out.flush();
            out.close();
        } else {
            System.out.println("Demo.example -------->" + "获取信息失败");
        }
    }

commons-httpclient

  • pom
    <dependency> 
        <groupId>apache-httpclient</groupId>
        <artifactId>commons-httpclient</artifactId>  
        <version>3.1</version> 
    </dependency>
  • demo

downloadByCommonsHttpclient

/**
     * 下载资源
     *
     * @param url
     * @param filePath
     * @throws IOException
     */
    public boolean getDownloadResource(String url, OutputStream out) throws IOException {

        long begin = System.currentTimeMillis();

        try {

            HttpClientParams httpClientParams = new HttpClientParams();
            httpClientParams.setSoTimeout(2000);
            httpClientParams.setConnectionManagerTimeout(2000);
            // http请求
            getHttpResponse(url, out, httpClientParams);

            out.flush();
            out.close();

            System.out.println("下载资源耗时:" + (System.currentTimeMillis() - begin));

            return true;
        } catch (Exception e) {
            return false;
        }
    }

getHttpResponse

/**
     * 根据url 获得http response返回结果OutputStream。
     * 
     * @param url
     * @param out
     * @param httpClientParams 不能为null,为null会抛出异常;至少new一个空对象放入
     * @return
     * @throws IOException
     */
    public static OutputStream getHttpResponse(String url, OutputStream out, HttpClientParams httpClientParams)
            throws IOException {

        if (url.indexOf("//") == -1) {
            url = "http://" + url;
        }
        HttpClient httpClient = getHttpClient(httpClientParams);
        GetMethod getMethod = new GetMethod(url);

        InputStream inputStream = null;
        try {
            getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
            // 执行
            int statusCode = httpClient.executeMethod(getMethod);
            if (statusCode != HttpStatus.SC_OK) {
                throw new IOException("connect url error:" + getMethod.getStatusLine() + " url: " + url);
            } else {
                inputStream = getMethod.getResponseBodyAsStream();
                IOUtils.copy(inputStream, out);
            }
        } catch (IOException e) {
            throw e;
        } finally {
            try {
                getMethod.releaseConnection();
            } catch (Exception e) {
                LOG.error(e.getMessage(), e);
            }
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (Exception e) {
                LOG.error(e.getMessage(), e);
            }
        }

        return out;
    }


getHttpClient


private static HttpClient getHttpClient(HttpClientParams httpClientParams) {
        HttpClient httpClient = new HttpClient(httpClientParams);
        if (httpClientParams.getConnectionManagerTimeout() > Integer.MAX_VALUE) {
            httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(Integer.MAX_VALUE);
        } else {
            httpClient.getHttpConnectionManager().getParams()
                    .setConnectionTimeout((int) httpClientParams.getConnectionManagerTimeout());
        }
        return httpClient;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值