欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

通过URL下载网络资源

程序员文章站 2022-05-05 20:42:41
...

有URL可以通过url类下载相关文件资源


public class URLdown {
    public static void main(String[] args) throws Exception {
        String UrlStr = "https://p1.music.126.net/NQCtUkal5sPxK1Y25SW3-Q==/109951165303077538.jpg?param=34y34";
        String FileName = "oula.jpg";
        URL url = new URL(UrlStr);

        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
        InputStream inputStream = urlConnection.getInputStream();
        FileOutputStream fos = new FileOutputStream(FileName);

        byte[] buffer = new byte[1024];
        int len;
        while ((len = inputStream.read(buffer)) != -1) {
            fos.write(buffer, 0, len);
        }
        fos.close();
        inputStream.close();
        urlConnection.disconnect();
    }
}

解释

  • UrlStr是URL字符串
  • FileName是需要保存的文件名
  • 没有权限的文件会报403
  • 与爬虫相似(大概)