zoukankan      html  css  js  c++  java
  • 原始http下载图片生成文件

    package com.example.demo.util;

    import java.io.*;
    import java.net.URL;
    import java.net.URLConnection;
    import java.util.Base64;

    public class DownLoadImg {
    public static void main(String[] args) throws IOException {
    String url = "https://gss1.bdstatic.com/9vo3dSag_xI4khGkpoWK1HF6hhy/baike/crop%3D0%2C1220%2C730%2C1000/sign=21562b92a8efce1bfe64928a9261dfef/1e30e924b899a901fdb1335212950a7b0308f5ca.jpg";
    //http下载图片
    byte[] arr = getInfo(url);
    byte[] brr = Base64.getEncoder().encode(arr);
    String str = new String(brr);
    System.out.println("落库字符串:" + str);
    //从数据库取出字符串解密 生成文件
    byte[] sss = Base64.getDecoder().decode(str.getBytes());
    File img = new File("abcd.jpg");
    img.createNewFile();
    FileOutputStream fileOutputStream = new FileOutputStream(img);
    fileOutputStream.write(sss);
    fileOutputStream.flush();
    fileOutputStream.close();
    System.out.println("生成图片完成...");
    }

    /**
    * get请求
    *
    * @param url
    * @return
    */
    public static byte[] getInfo(String url) {
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    InputStream in = null;
    try {
    String urlNameString = url;
    URL realUrl = new URL(urlNameString);
    URLConnection connection = realUrl.openConnection();
    connection.setRequestProperty("accept", "*/*");
    connection.setRequestProperty("connection", "Keep-Alive");
    connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
    connection.connect();
    in = connection.getInputStream();
    byte[] arr = new byte[2048];
    int count = 0;
    while ((count = in.read(arr)) != -1) {
    byteArrayOutputStream.write(arr, 0, count);
    }
    } catch (Exception e) {
    e.printStackTrace();
    } finally {
    try {
    if (in != null) {
    in.close();
    }
    } catch (Exception e2) {
    e2.printStackTrace();
    }
    return byteArrayOutputStream.toByteArray();
    }
    }
    }
  • 相关阅读:
    [Vue] #常见开发场景 #条件渲染#手动挂载 #组件方法的值驱动执行
    [JS高程] Typed Array 定型数组
    [JS高程]JavaScript中的RegExp对象
    [JS高程] Map 和 Set
    [JS高程] JavsScript 常用数组方法总结
    [JS高程] 字符串模式匹配方法
    自动化集成:Pipeline整合Docker容器
    自动化集成:Docker容器入门简介
    自动化集成:Jenkins管理工具详解
    分布式系统中,权限设计实践
  • 原文地址:https://www.cnblogs.com/coderdxj/p/12054630.html
Copyright © 2011-2022 走看看