java 网络文件下载,Java网络上下载文件

package net.onest.demo9;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.InputStream;

import java.net.HttpURLConnection;

import java.net.MalformedURLException;

import java.net.URL;

import java.net.URLConnection;

public class WenDemo {

public static void main(String[] args) {

try {

/*

* 使用URL访问网络资源只能读取数据不能输出资源,因为URL没有定义输出的方法

*/

URL url = new URL("http://www.baidu.com");//创建了一个URL类的对象

InputStream in = url.openStream();//获取网络资源的输入流对象

byte[] buffer = new byte[1024];

int len = 0;

//输出需要涉及字符串的拼接,所以使用StringBuffer类

StringBuffer strBuf = new StringBuffer();

while((len = in.read(buffer))!=-1) {

strBuf.append(new String(buffer,0,len));

}

System.out.println(strBuf.toString());

System.out.println(url.getPort());//端口号,没有指明端口号,默认为-1 URL url = new URL("http://www.baidu.com:80");自己加入端口号

System.out.println(url.getProtocol());//输出协议

System.out.println(url.getHost());//输出域名

in.close();

//URLConnection即可发送数据也可输出数据

//下载文件

URL imgURL = new URL("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1607830385997&di=90bf21fcc8c9deea8a2ab74c4ec73955&imgtype=0&src=http%3A%2F%2Fc3.haibao.cn%2Fimg%2F0_0_100_0%2F1532935240.8189%2F3694c22389c2c909103d8efee0acff98.jpg");

//URLConnection con = imgURL.openConnection();

//

//InputStream imgIn = con.getInputStream();//

//FileOutputStream fos = new FileOutputStream("F:/古力娜扎");//使用输出流没有必要去判断该文件是否存在,没有的话他会创建,有的话就覆盖

//byte[] imgBuff = new byte[1024];

//int lens = 0;

//while((lens = imgIn.read(imgBuff))!=-1) {

//fos.write(imgBuff,0,lens);

//}

//fos.close();

//imgIn.close();

//HttpURLConnection:对HTTP协议进行了封装,可以指定使用get请求还是post请求

HttpURLConnection httpURLConnection = (HttpURLConnection) imgURL.openConnection();

//对HTTP进行了封装,访问网络时可以指定某种HTTP请求方式(GET\POST\PUT\DELETE。。。。)

InputStream imgIn1 = httpURLConnection.getInputStream();//

FileOutputStream fos1 = new FileOutputStream("F:/古力娜扎");//使用输出流没有必要去判断该文件是否存在,没有的话他会创建,有的话就覆盖

byte[] imgBuff1 = new byte[1024];

int lens1 = 0;

while((lens1 = imgIn1.read(imgBuff1))!=-1) {

fos1.write(imgBuff1,0,lens1);

}

fos1.close();

imgIn1.close();

} catch (MalformedURLException e) {//传入的是一个错误的URL

e.printStackTrace();

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

}

本文地址:https://blog.csdn.net/weixin_52813580/article/details/112219789

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值