java利用httpclient包实现资源爬取到本地的功能(可直接调用)

package com.obcy.util;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

import java.io.*;

public class DownLoad {

//给定资源的绝对地址,和下载到的路径,可以直接下载资源

    public static void downLoad(String URL,String path) {

        //1.确定url
        String targetUrl = URL;
        //2.设置请求方式
        HttpGet hg = new HttpGet(targetUrl);
        hg.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36");
        //3.创建发送对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        //4.发送请求,获取响应对象
        //CloseableHttpResponse里面封装了响应头响应体响应行
        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute(hg);
        } catch (IOException e) {
            e.printStackTrace();
        }

        //5.解析响应对象
        if (response.getStatusLine().getStatusCode() == 200) {
            //获取响应体
            HttpEntity entity = response.getEntity();
            

            File f = new File(path);


            System.out.println("开始下载"+path);


            try {
                entity.writeTo(new BufferedOutputStream(new FileOutputStream(f)));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }else {
            System.out.println("这个资源不存在");
        }


        //休眠0.5秒
        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println(path+"下载完成");

        //关闭http
        try {
            httpClient.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值