public static void main(String[] args) throws Exception {
String urlPath= "url";
String url = getVideo(urlPath);
File file = new File(url);
if(file.exists()){
file.delete();
}
}
public static String getVideo(String urlPath) throws Exception{
//首先要获取请求的路径,路径就是要从网上获取的资源
URL url = new URL(urlPath);//建立URL类对象,抛出异常
HttpURLConnection conn =(HttpURLConnection)url.openConnection();//得到UrlConnection对象
conn.setRequestMethod("GET");//声明请求方式
conn.setConnectTimeout(6*1000);//设置连接超时
if(conn.getResponseCode() == 200){//如果结果是200,就代表他的请求是成功的
InputStream inputStream = conn.getInputStream();//得到服务器端传回来的数据,相对客户端为输入流
byte[] data = readInstream(inputStream);
String filePath = "d:\\"+Guid.newGuid()+".mp4";
File file = new File(filePath);
FileOutputStream outputStream = new FileOutputStream(file);
outputStream.write(data);
outputStream.close();
return filePath;
}
return "";
}
private static byte[] readInstream(InputStream inputStream) throws Exception{
ByteArrayOutputStream byteArrayOutPutStream = new ByteArrayOutputStream();//创建ByteArrayOutputStream类
byte[] buffer = new byte[10240];//声明缓存区
int length = -1;//定义读取的默认长度
while((length = inputStream.read(buffer))!= -1){
byteArrayOutPutStream.write(buffer,0,length);//把缓存区中的输入到内存中
};
byteArrayOutPutStream.close();//关闭输入流
inputStream.close();//关闭输入流
return byteArrayOutPutStream.toByteArray();//返回这个输入流的字节数组
}