HttpURLConnection.openConnection状态码302

今天根据URL,下载视频。

new URL(url1).openConnection() 的时候,用HttpURLConnection接,出现302,以至于后面取不到流,无法读流。

HttpURLConnection con = (HttpURLConnection) new URL(url1).openConnection();
con.setConnectTimeout(15000);
con.setReadTimeout(15000);
//有博文说是多次转发的问题,允许它自动重定向,我这边加上之后没啥用
con.setInstanceFollowRedirects(true);

后面是这样写的,才解决了问题。

/** 根据URL下载视频
     * @author yys
     * @date 2022/10/17 10:58
     * @param url1 下载地址,bdPath 文件保存路径
     * @return string
     */
    public String downVideo(String url1,String bdPath) throws Exception {
        Map<String, Object> queryJson = new HashMap<String, Object>();
        //example.getVideoUrl()这里就是获取视频的url。
        URL url = new URL(url1);
        //获取文件名称,并且此时的文件名是/开始的,所以先分割获取。
        String file = url.getFile();
        String[] split = file.split("/");
        HttpURLConnection con = null;
        //读文件流
        DataInputStream in = null;
        DataOutputStream out = null;
        try {
            // 获取文件流
            con = (HttpURLConnection) new URL(url1).openConnection();
            con.setConnectTimeout(15000);
            con.setReadTimeout(15000);
            con.setInstanceFollowRedirects(false);
            if (con.getResponseCode() == 302) {
                //如果会重定向,保存302重定向地址,以及Cookies,然后重新发送请求(模拟请求)
                String location = con.getHeaderField("Location");
                con.disconnect();
                url1 = location;
                con = (HttpURLConnection) new URL(url1).openConnection();
                con.setConnectTimeout(15000);
                con.setReadTimeout(15000);
            }
            int code = con.getResponseCode();
            if (code != HttpURLConnection.HTTP_OK) {
                queryJson.put("message","error");
                throw new Exception("文件读取失败");
            }
            //读文件流
            in = new DataInputStream(con.getInputStream());
            out = new DataOutputStream(new FileOutputStream(bdPath));
            byte[] buffer = new byte[2048];
            int count = 0;
            while ((count = in.read(buffer)) > 0) {
                out.write(buffer, 0, count);
            }
        }catch (IOException e) {
            throw new Exception("IOException...");
        }finally {
            out.close();
            in.close();
        }
        queryJson.put("message","success");
        return JSON.toJSONString(queryJson);
    }

  




posted @ 2022-10-17 13:48  90的生力军  阅读(350)  评论(0编辑  收藏  举报