http访问获取链接数据下载视频

今天需求开发新功能,视频原本是直接在本地点击上传,有数据源直接读取,上传到服务器。新功能让改成客户可以放一条视频链接,读取链接里面的视频。

我的思路就是,先用http请求读取链接,获取链接里面的信息,然后在吧链接里面的视频下载到本地,最后在调用直接的上传接口。本篇文章主要是介绍的是 http访问获取链接数据下载视频

先自己定义一个httpResult,用于接收请求返回的数据:

接下来就可以写代码:

 public static void main(String[] args) {
        interfaceUtil("https://www.baidu.com/", "");
    }
    /**
     * 调用对方接口方法
     * @param path 对方或第三方提供的路径
     * @param data 向对方或第三方发送的数据,大多数情况下给对方发送JSON数据让对方解析
     */
    public static void interfaceUtil(String path,String data) {
        try {
            URL url = new URL(path);
            //打开和url之间的连接
            HttpURLConnection conn = (HttpURLConnection)url.openConnection();
            PrintWriter out = null;
            //请求方式
            //          conn.setRequestMethod("POST");
            //           //设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
            //设置是否向httpUrlConnection输出,设置是否从httpUrlConnection读入,此外发送post请求必须设置这两个
            //最常用的Http请求无非是get和post,get请求可以获取静态页面,也可以把参数放在URL字串后面,传递给servlet,
            //post与get的 不同之处在于post的参数不是放在URL字串里面,而是放在http请求的正文内。
            conn.setDoOutput(true);
            conn.setDoInput(true);
            //获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            //发送请求参数即数据
            out.print(data);
            //缓冲数据
            out.flush();
            //获取URLConnection对象对应的输入流
            InputStream is = conn.getInputStream();
            //构造一个字符流缓存
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            String str = "";
            while ((str = br.readLine()) != null) {
                System.out.println(str);
            }
            //关闭流
            is.close();
            //断开连接,最好写上,disconnect是在底层tcp socket链接空闲时才切断。如果正在被其他线程使用就不切断。
            //固定多线程的话,如果不disconnect,链接会增多,直到收发不出信息。写上disconnect后正常一些。
            conn.disconnect();
            System.out.println("完整结束");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

/**
 * @author keying
 * @date 2021/5/10
 */
public class VideoHttpController {

    /**

     */

    public static void main(String[] args) throws Exception {
        String url = "";
        //String url = "https://www.baidu.com/";
        Map<String, Object> map = new HashMap<>();
        //map.put("id",22222);
        //map.put("name",33333);
        doGet(url, map);
    }

    public static String doGet(String url, Map<String, Object> map) throws Exception {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        // 声明URIBuilder
        URIBuilder uriBuilder = new URIBuilder(url);

        InputStream is = null;
        // 判断参数map是否为非空
        if (map != null) {
            // 遍历参数
            for (Map.Entry<String, Object> entry : map.entrySet()) {
                // 设置参数
                uriBuilder.setParameter(entry.getKey(), entry.getValue().toString());
            }
        }

        // 2 创建httpGet对象,相当于设置url请求地址
        HttpGet httpGet = new HttpGet(uriBuilder.build());

        // 3 使用HttpClient执行httpGet,相当于按回车,发起请求
        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute(httpGet);
        } catch (IOException e) {
            HttpResult httpResult = new HttpResult();
            httpResult.setCode(404);
            httpResult.setBody("请求失败");

        }
        // 4 解析结果,封装返回对象httpResult,相当于显示相应的结果
        // 状态码
        // response.getStatusLine().getStatusCode();
        // 响应体,字符串,如果response.getEntity()为空,下面这个代码会报错,所以解析之前要做非空的判断
        // EntityUtils.toString(response.getEntity(), "UTF-8");
        HttpResult httpResult = new HttpResult();
        // 解析数据封装HttpResult
        if (response.getEntity() != null) {
            //httpResult = new HttpResult(response.getStatusLine().getStatusCode(),EntityUtils.toString(response
            // .getEntity(),"UTF-8"));
            httpResult.setCode(response.getStatusLine().getStatusCode());
            HttpEntity entity = response.getEntity();
            is = entity.getContent();
            //httpResult.setBody(EntityUtils.toString(response.getEntity(), "UTF-8"));

        } else {
            //httpResult = new HttpResult(response.getStatusLine().getStatusCode(), "");
            httpResult.setCode(response.getStatusLine().getStatusCode());
            //httpResult.setBody("");
        }

        //创建文件
        File file = new File("/Users/keying/Downloads/zz.mp4");
        FileOutputStream fileOutputStream = new FileOutputStream(file);

        int len = 0 ;
        //创建字节数组 读取数组写入数组
        byte[] b = new byte[1024];
        while( (len = is.read(b)) !=-1){
            //System.out.print(new String(b,0,len));
            fileOutputStream.write(b, 0, len);
        }
        //释放资源
        fileOutputStream.close();
        // 返回
        return null;

    }

}

导入需要的jar:

 <!--添加httpClient jar包 -->
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
        </dependency>

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

后端从入门到精通

你的鼓励是我最大的动力~

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值