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();
    }
    }
    }
  • 相关阅读:
    字符串实现变量映射
    纯css实现无限嵌套菜单
    flex布局嵌套之高度自适应
    easy ui 零散技巧
    js高级应用
    前端利器
    css高级应用及问题记录(持续更新)
    兼容性验证方案
    原生js判断元素是否可见
    vue-cli webpack躺坑之旅
  • 原文地址:https://www.cnblogs.com/coderdxj/p/12054630.html
Copyright © 2011-2022 走看看