原始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();
}
}
}
posted @ 2019-12-17 15:06  洞玄巅峰  阅读(370)  评论(0编辑  收藏  举报