内存输入输出流(从网上下载版、爬)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_34195441/article/details/86170577

爬个视频/图片等(一般简单公开而已,特别加密就不行了,哎那有什么用呢> _ <):

找到视频页面,右键审查元素,1)html中<image>中url、<video>中视频 or

2)network->XHR->?rs找视频路径

3)爬到之后下到本地

package com.hpu.download;

import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * url统一资源定位符
 * 内存输入输出流
 * @author Administrator
 *
 */
public class TestDownload {
	public static void main(String[] args) {
		//爬到小猪佩奇了啊哈
		String urlPath="https://v11-tt.ixigua.com/d2055bdf5afc8a6f0b1c5e19e0bba72e/5c35d633/video/m/2206dd44c37f3c446f0b87ff87167e3b1f71161354b2000033b8959e4c1b/?rc=MztoOzt1Z291ajMzZTczM0ApQHRAbzUzNjU6MzQzMzczNDMzNDVvQGgzdSlAZjN1KWRzcmd5a3VyZ3lybHh3Zjc2QDBkbzIzL2Fkal8tLTUtL3NzLW8jbyM2NS0vLzEtLjMzNTYuNi06I28jOmEtcSM6YHZpXGJmK2BeYmYrXnFsOiMzLl4%3D&vfrom=xgplayer";
		//本地存放视频
		String targetPath="小猪佩奇.mp4";
		//将网络资源转换为字节数组,存在内存中
		byte [] data=formNetworkDownloadSource(urlPath);
		//将字节数组生成本地对应的文件
		save(data,targetPath);
	}
    
	//连接网络并将视频内容转换为字节数组
	private static byte[] formNetworkDownloadSource(String urlPath) {
		try {
			//将视频路径转换为url对象
			URL url=new URL(urlPath);
			//获取内存输出流
			ByteArrayOutputStream byteOut=new ByteArrayOutputStream();
			//通过url对象获取输入流读取网络资源
			InputStream input=url.openStream();
			//缓冲区
			byte [] buffer=new byte[1024];
			int length=0;
			while((length=input.read(buffer))!=-1){
				byteOut.write( buffer,0, length);
			}
			return byteOut.toByteArray();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

    //本地生成视频文件
	private static void save(byte[] data, String targetPath) {
		FileOutputStream outputStream=null;
		try {
			outputStream = new FileOutputStream(targetPath);
			outputStream.write(data);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			if(outputStream!=null){
				try {
					outputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}	
	}
}

猜你喜欢

转载自blog.csdn.net/qq_34195441/article/details/86170577