使用java怎么下载Http内容

  介绍

使用java怎么下载Http内容?相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。

java是什么

java是一门面向对象编程语言,可以编写桌面应用程序,网络应用程序,分布式系统和嵌入式系统应用程序。

<强> 1,下载流程

在互联网上,我们要下载网站上的某一个资源,我们会获得一个你的L (UniformResou远端控制设备定位器),它是一个服务器资源定位的描述,下载的过程经常如下方法:

(1)客户端发起连接请求一个URL

(2)服务器解析URL,并将指定的资源返回一个输入流给客户

(3)客户端接收输入流,将流中的内容存到文件

<强> 2,实例

 package  com.hu.down;
  ,
  import  java.io.BufferedInputStream;
  import  java.io.BufferedOutputStream;
  import  java.io.File;
  import  java.io.FileNotFoundException;
  import  java.io.FileOutputStream;
  import  java.io.IOException;
  import  java.net.HttpURLConnection;
  import  java.net.MalformedURLException;
  import  java.net.URL;
  ,
  public  class  DownFile  {
  ,
  public  final  static  boolean  DEBUG =,真的,,//调试用
  ,,,private  static  int  BUFFER_SIZE =, 1024,,//缓冲区大小
  ,,,,
  ,,,public  void  saveToFile (String  destUrl) {
  ,,,,
  ,,,,,,,BufferedInputStream  bis =,空;
  ,,,,,,,HttpURLConnection  httpUrl =,空;
  ,,,,,,,URL  URL =,空;
  ,,,,,,,byte [], buf =, new 字节(BUFFER_SIZE);
  ,,,,,,,
  ,,,,,,,try  {
  时间=url  new  URL (destUrl);
  },catch  (MalformedURLException  e), {//,TODO  Auto-generated  catch 块
  System.out.println (destUrl +“资源URL语法错误,请检查字符串是否正确!“);
  返回;
  }
  ,,,,,,,try  {
  httpUrl =, (HttpURLConnection), url.openConnection ();
  },catch  (IOException  e), {
  System.out.println(“打开到,“+ destUrl +“所引用的远程对象的连接失败“);
  }
  ,,,,,,,
  ,,,,,,,try  {
  httpUrl.connect ();
  },catch  (IOException  e), {
  System.out.println(“打开到此,“+ destUrl +“,引用的资源的通信链接失败“);
  返回;
  }
  ,,,,,,,
  ,,,,,,,
  ,,,,,,,try  {
  时间=bis  new  BufferedInputStream (httpUrl.getInputStream ());
  },catch  (IOException  e), {
  System.out.println(“取得连接的输入流失败“);
  返回;
  }
  ,,,,,,,
  ,,,,,,,File  File =, new 文件(“D:/upload", +, destUrl.substring (destUrl.lastIndexOf (“/?));
  ,,,,,,,
  ,,,,,,,BufferedOutputStream  fileOut=零;
  try  {
  时间=fileOut  new  BufferedOutputStream (new  FileOutputStream(文件);
  },catch  (FileNotFoundException  e), {
  System.out.println(文件+“在本地保存文件失败“);
  e.printStackTrace ();
  }
  ,,,,,,,试着{
  ,,,,,,,,while (真实),{
  ,,,,,,,,,,,,,,,int  bytesIn =, bis.read (buf, 0, 1024);
  ,,,,,,,,,,,,,,,if  (==bytesIn  1), {
  ,,,,,,,,,,,,,,,,,,休息;
  ,,,,,,,,,,,,,,,},{else 
  ,,,,,,,,,,,,,,,,,,fileOut.write (buf, 0, bytesIn);
  ,,,,,,,,,,,,,,,}
  ,,,,,,,,,,,,}
  ,,,,,,,,,,,,
  ,,,,,,,,,,,,fileOut.flush ();
  ,,,,,,,,,,,,fileOut.close ();
  ,,,,,,,}捕捉(Exception  ee) {
  ,,,,,,,,System.out.println(文件+“保存文件过程失败“);
  ,,,,,,,}
  ,,,,,,,,System.out.println (file.getAbsolutePath() +“下载完毕“);
  ,,,,,,,
  ,,,}
  null
  null
  null
  null
  null
  null
  null
  null
  null
  null
  null

使用java怎么下载Http内容