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();
    }
    }
    }
  • 相关阅读:
    Mysql Explain 详解
    TP5和TP3.2的区别
    Http协议详解
    TCP协议三次握手与四次挥手详解
    一些常规面试问题
    计算机网络常识
    队列与栈的区别
    面向对象
    在浏览器中输入 www.baidu.com 后执行的全部过程
    SVN在ubuntu的安装和使用
  • 原文地址:https://www.cnblogs.com/coderdxj/p/12054630.html
Copyright © 2011-2022 走看看