url下载文件(重定向+cookie设置)

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

很多时候,下载文件时会重定向,并且要求携带cookie才允许下载,这种情况下,如果让下载支持重定向,并且设置cookie呢?下面的代码可以供大家参考。

    public static void main(String[] args) throws Exception {
        String cookie = "";
        HttpURLConnection conn = null;
        do {
            URL url = new URL("***");
            conn = (HttpURLConnection) url.openConnection();
            //设置超时间为3秒
            conn.setConnectTimeout(3*1000);
            //防止屏蔽程序抓取而返回403错误
            conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
            conn.setInstanceFollowRedirects(false);
            if (cookie.length() != 0) {
                conn.setRequestProperty("Cookie", cookie);
            }
            int code = conn.getResponseCode();
            if (code == HttpURLConnection.HTTP_MOVED_TEMP) {
                for (int i = 1; i < conn.getHeaderFields().size(); i++) {
                    if (conn.getHeaderFieldKey(i).equalsIgnoreCase("set-cookie")) {
                        cookie += conn.getHeaderField(i) + ";";
                    }
                }
            }
            if (conn.getResponseCode() == HttpURLConnection.HTTP_OK)
                break;
        } while(true);

        //得到输入流
        InputStream inputStream = conn.getInputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while((len = inputStream.read(buffer)) != -1) {
            System.out.println(len);
        }
        if(inputStream!=null){
            inputStream.close();
        }
    }

猜你喜欢

转载自blog.csdn.net/pingnanlee/article/details/80246965