网络图片解析上传oss

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.Map;

public class uploadFile {

    public static void main(String[] args) {

        //网络图片地址
        String fileUrl = "https://pics7.baidu.com/feed/d788d43f8794a4c23cd99e759a35abd3ac6e3939.jpeg?token=f76c797c6cdfd571cc11349aa280ded4";
        InputStream imageStream = getImageStream(fileUrl);
        //oss地址
        String ossUrl = "https://xxx.com/oss/upload";
        try {
            JSONObject json = uploadFile(".png", ossUrl, imageStream);
            System.out.println(json);
        } catch (Exception ex) {
            ex.printStackTrace();
        }


    }

    public static InputStream getImageStream(String url) {
        try {
            HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
            connection.setReadTimeout(5000);
            connection.setConnectTimeout(5000);
            connection.setRequestMethod("GET");
            if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                InputStream inputStream = connection.getInputStream();
                return inputStream;
            }
        } catch (IOException e) {
            System.out.println("获取网络图片出现异常,图片路径为:" + url);
            e.printStackTrace();
        }
        return null;
    }

    public static JSONObject uploadFile(String fileName, String ossUrl, InputStream imageStream) throws Exception {
        // 换行符
        final String newLine = "\r\n";
        final String boundaryPrefix = "--";
        // 定义数据分隔线
        String BOUNDARY = "========7d4a6d158c9";
        // 服务器的域名
        URL url = new URL(ossUrl);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        // 设置为POST情
        conn.setRequestMethod("POST");
        // 发送POST请求必须设置如下两行
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setUseCaches(false);
        // 设置请求头参数
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.setRequestProperty("Charset", "UTF-8");
        conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
        try (
                OutputStream outputStream = conn.getOutputStream();
                DataOutputStream out = new DataOutputStream(outputStream);
        ) {
            // 上传文件
            StringBuilder sb = new StringBuilder();
            sb.append(boundaryPrefix);
            sb.append(BOUNDARY);
            sb.append(newLine);
            sb.append("Content-Disposition: form-data;name=\"file\";filename=\"").append(fileName)
                    .append("\"").append(newLine);
            sb.append("Content-Type:application/octet-stream");
            sb.append(newLine);
            sb.append(newLine);
            out.write(sb.toString().getBytes());

            try (DataInputStream in = new DataInputStream(imageStream);) {
                byte[] bufferOut = new byte[1024];
                int bytes = 0;
                while ((bytes = in.read(bufferOut)) != -1) {
                    out.write(bufferOut, 0, bytes);
                }
                out.write(newLine.getBytes());
            } catch (Exception e) {
                e.printStackTrace();
            }
            // 定义最后数据分隔线,即--加上BOUNDARY再加上--。
            byte[] end_data = (newLine + boundaryPrefix + BOUNDARY + boundaryPrefix + newLine)
                    .getBytes();
            // 写上结尾标识
            out.write(end_data);
            out.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }

        //定义BufferedReader输入流来读取URL的响应
        try (
                InputStream inputStream = conn.getInputStream();
                InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
                BufferedReader reader = new BufferedReader(inputStreamReader);
        ) {
            String line = null;
            StringBuffer sb = new StringBuffer();
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
            return JSONObject.parseObject(sb.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null ;
    }

}

 解析并上传返回oss地址

猜你喜欢

转载自www.cnblogs.com/1-Admin/p/12925546.html