java通過http請求獲取文件二進制流生產文件

聲明:根據http請求圖片的url下載文件到本地

 

public void  downLoadPhoto(String photoUrl)throws Exception{
         
        //獲取照片返回二進制流
            RestTemplate restTemplate = new RestTemplate();
            HttpHeaders headers = new HttpHeaders();
            ResponseEntity<byte[]> entity = restTemplate.exchange(photoUrl, HttpMethod.GET,new HttpEntity<>(headers), byte[].class);
            byte[] body = entity.getBody();
            InputStream sbs = new ByteArrayInputStream(body);

            File dest = new File("/Users/qixin/Desktop/a.jpg");
            if(!dest.exists()) {
                dest.createNewFile();
            }

            InputStream in = null;
            OutputStream out = null;

            in = new ByteArrayInputStream(body);
            out = new FileOutputStream(dest);

            byte []bt = new byte[1024];
            int length=0;
            while(	(length = in.read(bt)) !=-1) {
                //一次性寫入文件a中
                out.write(bt,0,length);
            }

            if(null!=out) {
                out.close();
            }



 }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章