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