示例#1
0
  public static void readURL(String urlString, int bufferSize) throws IOException {

    System.out.println("start=" + new Date());
    long start = System.currentTimeMillis();

    URL url;
    java.io.InputStream is = null;
    try {
      url = new URL(urlString);
    } catch (MalformedURLException e) {
      throw new IOException(
          "** MalformedURLException on URL <" + urlString + ">\n" + e.getMessage() + "\n");
    }

    try {
      java.net.HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();
      // check response code is good
      int responseCode = httpConnection.getResponseCode();
      System.out.println(" response code= " + responseCode);
      if (responseCode / 100 != 2)
        throw new IOException(
            "** Cant open URL <"
                + urlString
                + ">\n Response code = "
                + responseCode
                + "\n"
                + httpConnection.getResponseMessage()
                + "\n");

      // read it
      is = httpConnection.getInputStream();

      int nreads = 0;
      long totalB = 0;
      long total = 0;
      byte[] buffer = new byte[bufferSize];
      while (true) {
        int bytesRead = is.read(buffer);
        if (bytesRead == -1) break;
        totalB += bytesRead;
        total += buffer[0]; // prevent compiler optimization
        nreads++;
      }
      double took = .001 * (System.currentTimeMillis() - start);
      double rate = totalB / took / (1000 * 1000);
      double avg = totalB / nreads;
      System.out.println(
          " readURL ("
              + bufferSize
              + ") took = "
              + took
              + " sec; rate = "
              + rate
              + "Mb/sec avg read= "
              + avg);
      System.out.println("   dummy=" + total);
      System.out.println(" end=" + new Date());

    } catch (java.net.ConnectException e) {
      throw new IOException(
          "** ConnectException on URL: <"
              + urlString
              + ">\n"
              + e.getMessage()
              + "\nServer probably not running");

    } finally {
      if (is != null) is.close();
    }
  }