package cn.hp.demo01; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.RandomAccessFile; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; /** * 直接下载 * http://softforspeed.51xiazai.cn/down/BaiduNetdisk_6.9.7.4.exe */ public class Demo02 { public static void main(String[] args) { String path = "https://pm.myapp.com/invc/xfspeed/qqpcmgr/download/QQPCDownload1843.exe"; try { //创建一个URL对象 URL url = new URL(path); //打开连接,获取了url请求的连接对象conn HttpURLConnection conn = (HttpURLConnection) url.openConnection(); //请求设置 conn.setConnectTimeout(5000);//请求的超时时间 conn.setReadTimeout(5000);//读取超时时间 conn.setRequestMethod("GET");//设置请求提交的方法Get Post //获取响应码 int responseCode = conn.getResponseCode();//获取响应码 System.out.println("responseCode = " + responseCode); //如果连接ok 200 if(responseCode==200){ //下载? InputStream in = conn.getInputStream();//获取用于读取网络资源的输入流 //下载的流 //String fileName = conn.getHeaderField("Content-Disposition");//获取响应的头部文件(包含由文件名) //fileName = fileName.split(";")[1]; //fileName = fileName.substring(fileName.indexOf("\"")+1,fileName.lastIndexOf("\"")); //System.out.println(fileName);//成功获取文件名 File file = new File("QQPCDownload1843.exe"); RandomAccessFile raf = new RandomAccessFile(file,"rwd");//可读、可写,有权限 //读一组,下载一组 byte[]bytes=new byte[1024]; int len = 0; while((len=in.read(bytes))!=-1){ raf.write(bytes,0,len); } //关闭流释放资源 raf.close(); in.close(); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
直接下载 * http://softforspeed.51xiazai.cn/down/BaiduNetdisk_6.9.7.4.exe
关键词由优快云通过智能技术生成