欢迎来到代码驿站!

JAVA代码

当前位置:首页 > 软件编程 > JAVA代码

Java 根据url下载网络资源

时间:2021-08-10 09:24:39|栏目:JAVA代码|点击:

URL:统一资源定位符

例如:https://www.baidu.com

URL【统一资源定位符】:定位资源的,定位互联网上的某一个资源。

DNS 域名解析:www.baidu.com【某一域名】指向 39.156.69.79【某一网站空间IP】

URL 组成:协议://ip地址:端口/项目名/资源

package lesson04;

import java.net.MalformedURLException;
import java.net.URL;

/**
 * URL:统一资源定位符
 */
public class URLDemo1 {

 public static void main(String[] args) throws MalformedURLException {
  URL url = new URL("http://localhost:8080/helloworld/index.jsp?username=kuangshen&password=123");
  //协议名
  System.out.println(url.getProtocol());
  //主机名-主机ip
  System.out.println(url.getHost());
  //端口
  System.out.println(url.getPort());
  //地址-文件路径
  System.out.println(url.getPath());
  //文件-全路径
  System.out.println(url.getFile());
  //查询部分-参数
  System.out.println(url.getQuery());
 }

}

URL下载资源

package lesson04;

import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * URL下载资源
 */
public class URLDown {

 public static void main(String[] args) throws Exception {
  //1、下载地址
  URL url = new URL("https://m10.music.126.net/20201121104035/2c5eb73ce4421a090b62647f6c486e2c/yyaac/obj/wonDkMOGw6XDiTHCmMOi/3625445007/7d37/4109/d0ef/d56e8176f5789a4e6f8b2173ce500bf6.m4a");

  //2、连接到这个资源 HTTP
  HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

  InputStream inputStream = urlConnection.getInputStream();

  FileOutputStream fos = new FileOutputStream("f6.m4a");

  byte[] buffer = new byte[1024];
  int len;
  while ((len = inputStream.read(buffer)) != -1){
   fos.write(buffer, 0, len); //写出这个数据
  }

  //关闭
  fos.close();
  inputStream.close();

  //断开连接
  urlConnection.disconnect();
 }

}

效果一览

上一篇:SpringBoot多数据源配置详细教程(JdbcTemplate、mybatis)

栏    目:JAVA代码

下一篇:java 生成二维码实例

本文标题:Java 根据url下载网络资源

本文地址:http://www.codeinn.net/misctech/165643.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有