功能:HTTP是客户端浏览器或其他程序与Web服务器之间的应用层通信协议
SP:空格
CRLF:换行
URI:包含UTL 统一资源标识符 /index.html
URL:统一资源定位符 http://www.baidu.com:80/index.html
URN:统一资源名 比如QQ邮箱
URI=URL+URN
请求的报头:请求的环境
实例:
package com.yc.net.http01;
import java.io.BufferedOutputStream;
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.text.NumberFormat;
public class XueLei01 {
public static void main(String[] args) {
try {
URL url=new URL("http://dlsw.baidu.com/sw-search-sp/soft/ca/13442/Thunder_dl_7.9.41.5020_setup.1444900082.exe");
HttpURLConnection con=(HttpURLConnection) url.openConnection();//获得连接对象
// con.setRequestMethod("HEAD"); //设置请求方式 head get post.....
con.setRequestMethod("GET");
con.connect();//建立连接
int responseCode=con.getResponseCode();//获取响应
if(responseCode==200){
System.out.println("连接成功");
long totalSize=con.getContentLengthLong();// 文件总长度
long downloadSize=0;//下载的长度
//保存到本地磁盘的字节输出缓存流
BufferedOutputStream out=new BufferedOutputStream(new FileOutputStream("d:\\Thunder.exe"));
InputStream in=con.getInputStream();//获得响应的实体内容 单线程下载
byte[] bs=new byte[1024*1024]; //以M为单位下载
int length=0;
while((length=in.read(bs))!=-1){
out.write(bs,0,length);//写入到文件
downloadSize+=length;//累加下载长度
System.out.println("下载长度为"+(downloadSize *100.0/totalSize)+"%");
}
out.flush();
out.close();
in.close();
System.out.println("下载成功");
}else{
System.out.println(con.getResponseMessage());//获得响应码 获得响应信息
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}