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();
    }
    }
    }
  • 相关阅读:
    matplotlib讲义
    车间调度问题(part3: 遗传算法)
    sympy库和matplotlib库简介
    python列表
    第十周周三练习
    第十一周周一练习题
    MyEcplise中关于部署文件不成功的问题
    Java中的get()和set()方法
    Java中this关键字的使用
    信号完整性问题的几个基本原则
  • 原文地址:https://www.cnblogs.com/coderdxj/p/12054630.html
Copyright © 2011-2022 走看看