package edu.wtbu;
import java.net.MalformedURLException;
import java.net.URL;
public class Demo01 {
//URL:统一资源定位符:定位互联网上的某一个资源
//URL=协议://ip:port/项目名
public static void main(String[] args) throws MalformedURLException {
URL url = new URL("http://localhost:8080/helloworld/index.jsp?username=duhao&password=123456");
System.out.println(url.getProtocol());//协议
System.out.println(url.getHost());//ip
System.out.println(url.getPort());//端口
System.out.println(url.getPath());//文件
System.out.println(url.getFile());//全路径
System.out.println(url.getQuery());//参数
}
}
package edu.wtbu;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class Demo02 {
public static void main(String[] args) throws IOException {
//1.下载地址
URL url = new URL("http://localhost:8080/duhao/good.txt");
//2.连接到这个资源 HTTP
HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
InputStream is = urlConnection.getInputStream();
FileOutputStream fos = new FileOutputStream("good.txt");
byte[] bytes = new byte[1024];
int len;
while ((len=is.read())!=-1){
fos.write(bytes,0,len);//写出这个数据
}
fos.close();
is.close();
urlConnection.disconnect();//断开连接
}
}