java下载网络图片

9 篇文章 0 订阅

 一、下载图片至本地示例代码

public class DownloadImage {

    public static void main(String[] args) throws IOException {
        // 下载到指定目录
        File img = new File("D:\\tmp\\20100817072651150.jpg");
        URL url = new URL("https://gerenziliao.os8.cn/hdos/UploadFiles/2010-08/admin/20100817072651150.jpg");
        URLConnection urlConnection = url.openConnection();
        urlConnection.connect();
        try (InputStream inputStream = urlConnection.getInputStream();
             BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
             OutputStream out = new FileOutputStream(img);
             BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(out)) {


            byte[] buffer = new byte[1024];//每次读取/写入大小是1k
            for (int len = 0; (len = bufferedInputStream.read(buffer)) > 0; ) {
                bufferedOutputStream.write(buffer, 0, len);
                // bufferedOutputStream关闭时会自动刷新,否则需显示调用该方法
                // bufferedOutputStream.flush();
            }
        }
    }
}

通过Java HTTP连接将网络图片下载到本地

httpClient4.2官方文档研究

JAVA压缩图片并打成ZIP

二、Java代理 GET 访问示例代码

    /**
     * 使用Java发送get 代理请求
     *
     * @param url url
     * @return {@link String}
     * @throws IOException IO异常
     */
    protected String getWithJava(String url) throws IOException {
        // 设置代理服务器的地址和端口
        String proxyHost = "109.246.120.208";
        int proxyPort = 1234;

        // 创建代理对象
        Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort));

        // 创建连接
        URL address = restTemplate.getUriTemplateHandler().expand(url).toURL();
        HttpURLConnection conn = (HttpURLConnection) address.openConnection(proxy);

        // 设置请求方法和超时时间
        conn.setRequestMethod("GET");
        conn.setConnectTimeout(5000);
        conn.setReadTimeout(5000);
        // 头信息 USER_AGENT 设置好像不生效,待验证
        conn.setRequestProperty(HttpHeaders.USER_AGENT, USER_AGENT[ThreadLocalRandom.current().nextInt(USER_AGENT.length)]);

        // 读取数据
        try (InputStream inputStream = conn.getInputStream();
             InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
             BufferedReader in = new BufferedReader(inputStreamReader)) {
            String inputLine;
            StringBuilder response = new StringBuilder();
            while (Objects.nonNull(inputLine = in.readLine())) {
                response.append(inputLine);
            }
            return response.toString();
        }
    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值