java http远程调用接口下载文件

远程调用http接口下载文件,接口返回流

一、将文件保存本地

public String httpDownload(String httpUrl){
    try {
        URL url = new URL(httpUrl) ;
        //filePath文件地址,fileName文件名
        File file = new File(filePath, fileName);
        FileUtils.copyURLToFile(url,file);
    } catch (IOException e) {
        logger.info("用印文件下载失败:{}",e.getMessage());
        return null;
    }
    //文件地址
    return basePath + "/" + fileName;
}

二、将接收到流直接返回

public void httpDownload(String httpUrl,HttpServletResponse response)throws IOException{
        URL url = new URL(httpUrl) ;
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection() ;
        urlConnection.connect() ;
        OutputStream outputStream = response.getOutputStream();
        InputStream inputStream = urlConnection.getInputStream() ;
        IOUtils.copy(inputStream,outputStream);
        inputStream.close();
        response.flushBuffer();
        outputStream.close();
}

你可能感兴趣的:(JAVA工具类,java,http,开发语言)