电脑技术学习

Java实现基于http协议的网络文件下载

dn001

  //读取网络文件,写入指定的文件中

  while ((nRead = input.read(b, 0, 1024)) > 0

  && nStartPos < nEndPos ) {

  oSavedFile.write(b, 0, nRead);

  nStartPos += nRead;

  }

  httpConnection.disconnect();

  } catch (Exception e) {

  e.printStackTrace();

  }

  }

  //; 获得文件长度

  public static long getFileSize(String sURL) {

  int nFileLength = -1;

  try {

  URL url = new URL(sURL);

  HttpURLConnection httpConnection = (HttpURLConnection) url

  .openConnection();

  httpConnection.setRequestProperty("User-Agent", "Internet Explorer");

  int responseCode = httpConnection.getResponseCode();

  if (responseCode >= 400) {

  System.err.println("Error Code : " + responseCode);

  return -2; // -2 represent access is error

  }

  String sHeader;

  for (int i = 1i++) {

  sHeader = httpConnection.getHeaderFieldKey(i);

  if (sHeader != null) {

  if (sHeader.equals("Content-Length")) {

  nFileLength = Integer.parseInt(httpConnection

  .getHeaderField(sHeader));

  break;

  }

  } else

  break;

  }

  } catch (IOException e) {

  e.printStackTrace();

  } catch (Exception e) {

  e.printStackTrace();

  }

  System.out.println(nFileLength);

  return nFileLength;

  }

  }

标签: