HttpURLConnection下載文件流


package com.loan.modules;

import sun.net.www.protocol.file.Handler;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
public class test333 {


    public static void main(String[] args) throws IOException {
        URL httpurl=new URL("http://yingufile-private.oss-cn-beijing.aliyuncs.com/PHYY/jpg/20170628/a85ab00c645e4b89dc38f3b8bb63a4f3");
        HttpURLConnection httpConn=(HttpURLConnection)httpurl.openConnection();
        httpConn.setDoOutput(true);// 使用 URL 連接進行輸出
        httpConn.setDoInput(true);// 使用 URL 連接進行輸入
        httpConn.setUseCaches(false);// 忽略緩存
        httpConn.setRequestMethod("GET");// 設置URL請求方法
        //可設置請求頭
        httpConn.setRequestProperty("Content-Type", "application/octet-stream");
        httpConn.setRequestProperty("Connection", "Keep-Alive");// 維持長連接
        httpConn.setRequestProperty("Charset", "UTF-8");
        //可設置請求頭


        byte[] file =input2byte(httpConn.getInputStream());
        writeBytesToFile(file,"D://333.png");
        System.out.println(file);
    }

    public static final byte[] input2byte(InputStream inStream)
            throws IOException {
        ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
        byte[] buff = new byte[100];
        int rc = 0;
        while ((rc = inStream.read(buff, 0, 100)) > 0) {
            swapStream.write(buff, 0, rc);
        }
        byte[] in2b = swapStream.toByteArray();
        return in2b;
    }

    public static File writeBytesToFile(byte[] b, String outputFile) {
        File file = null;
        FileOutputStream os = null;

        try {
            file = new File(outputFile);
            os = new FileOutputStream(file);
            os.write(b);
        } catch (Exception var13) {
            var13.printStackTrace();
        } finally {
            try {
                if(os != null) {
                    os.close();
                }
            } catch (IOException var12) {
                var12.printStackTrace();
            }

        }

        return file;
    }

}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM