(java)从url获取图片并且根据二进制上传到另外一个接口

没研究过通过base64码上传图片的,之前遇到一个需要二进制上传的需求,查了下网上的怎么上传的并且缝合了一个版本(主要当时一直搜没搜到)

public static DataInputStream getPictureDataInputStream(String path) {
    try {
        URL url = new URL("https://" + path);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setConnectTimeout(5 * 1000);
        return new DataInputStream(url.openStream());
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}
public static String sendPhoto(DataInputStream dataInputStream, String filename) {
    String end = "\r\n";
    String twoHyphens = "--";
    // 这个不一定要时间戳
    long boundary = LocalDateTime.now().toInstant(ZoneOffset.ofHours(8)).toEpochMilli();

    DataOutputStream ds = null;
    InputStream inputStream = null;
    InputStreamReader inputStreamReader = null;
    BufferedReader reader = null;
    StringBuffer resultBuffer = new StringBuffer();
    String tempLine = null;
    try {
        // 跳过SSL认证
        HostnameVerifier hv = (urlHostName, session) -> true;
        //  配置认证管理器
        javax.net.ssl.TrustManager[] trustAllCerts = {new WebV2Utils.TrustAllTrustManager()};
        SSLContext sc = SSLContext.getInstance("SSL");
        SSLSessionContext sslsc = sc.getServerSessionContext();
        sslsc.setSessionTimeout(0);
        sc.init(null, trustAllCerts, null);
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
		//  **主机认证
        HttpsURLConnection.setDefaultHostnameVerifier(hv);

        // 统一资源
        URL url = new URL("xxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
        // 连接类的父类,抽象类
        URLConnection urlConnection = url.openConnection();
        // http的连接类
        HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;
        // 设置是否从httpUrlConnection读入,默认情况下是true;
        httpURLConnection.setDoInput(true);
        // 设置是否向httpUrlConnection输出
        httpURLConnection.setDoOutput(true);
        // Post 请求不能使用缓存
        httpURLConnection.setUseCaches(false);
        // 设定请求的方法,默认是GET
        httpURLConnection.setRequestMethod("POST");

        // setRequestProperty基本上是head头里的东西
        // 设置字符编码连接参数
        httpURLConnection.setRequestProperty("Connection", "Keep-Alive");
        // 设置字符编码
        httpURLConnection.setRequestProperty("Charset", "UTF-8");
        // 设置请求内容类型
        httpURLConnection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);

        // 设置DataOutputStream
        ds = new DataOutputStream(httpURLConnection.getOutputStream());

        ds.writeBytes(twoHyphens + boundary + end);
        ds.writeBytes("Content-Disposition: form-data;");
        ds.writeBytes(end + end);
        ds.writeBytes(twoHyphens + boundary + end);
        ds.writeBytes("Content-Disposition: form-data; name=\"file\"; filename=\"" + filename + "\"" + end);
        ds.writeBytes("Content-Type: image/jpeg");
        ds.writeBytes(end);

        int bufferSize = 1024;
        byte[] buffer = new byte[bufferSize];
        int length = -1;
        while ((length = dataInputStream.read(buffer)) != -1) {
            ds.write(buffer, 0, length);
        }
        ds.writeBytes(end);
        /* close streams */
        dataInputStream.close();
        ds.writeBytes(twoHyphens + boundary + twoHyphens);
        ds.writeBytes(end);
        /* close streams */
        ds.flush();
        if (httpURLConnection.getResponseCode() >= 300) {
            throw new Exception(
                    "HTTP Request is not success, Response code is " + httpURLConnection.getResponseCode());
        }
        System.out.println(httpURLConnection.getResponseCode());
        if (httpURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
            inputStream = httpURLConnection.getInputStream();
            inputStreamReader = new InputStreamReader(inputStream);
            reader = new BufferedReader(inputStreamReader);
            tempLine = null;
            resultBuffer = new StringBuffer();
            while ((tempLine = reader.readLine()) != null) {
                resultBuffer.append(tempLine);
                resultBuffer.append("\n");
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (ds != null) {
            try {
                ds.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        if (inputStreamReader != null) {
            try {
                inputStreamReader.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return resultBuffer.toString();
    }
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值