Download file via http using Java


/ Published in: Java
Save to your folder(s)

This thread downloads file via url.


Copy this code and paste it in your HTML
  1. package core.spider;
  2.  
  3. import java.io.*;
  4. import java.net.*;
  5. import java.util.*;
  6.  
  7. // This class downloads a file from a URL.
  8. class Download extends Observable implements Runnable {
  9.  
  10. // Max size of download buffer.
  11. private static final int MAX_BUFFER_SIZE = 1024;
  12.  
  13. // These are the status names.
  14. public static final String STATUSES[] = {"Downloading",
  15. "Paused", "Complete", "Cancelled", "Error"};
  16.  
  17. // These are the status codes.
  18. public static final int DOWNLOADING = 0;
  19. public static final int PAUSED = 1;
  20. public static final int COMPLETE = 2;
  21. public static final int CANCELLED = 3;
  22. public static final int ERROR = 4;
  23.  
  24. private URL url; // download URL
  25. private int size; // size of download in bytes
  26. private int downloaded; // number of bytes downloaded
  27. private int status; // current status of download
  28.  
  29. // Constructor for Download.
  30. public Download(URL url) {
  31. this.url = url;
  32. size = -1;
  33. downloaded = 0;
  34. status = DOWNLOADING;
  35.  
  36. // Begin the download.
  37. download();
  38. }
  39.  
  40. // Get this download's URL.
  41. public String getUrl() {
  42. return url.toString();
  43. }
  44.  
  45. // Get this download's size.
  46. public int getSize() {
  47. return size;
  48. }
  49.  
  50. // Get this download's progress.
  51. public float getProgress() {
  52. return ((float) downloaded / size) * 100;
  53. }
  54.  
  55. // Get this download's status.
  56. public int getStatus() {
  57. return status;
  58. }
  59.  
  60. // Pause this download.
  61. public void pause() {
  62. status = PAUSED;
  63. stateChanged();
  64. }
  65.  
  66. // Resume this download.
  67. public void resume() {
  68. status = DOWNLOADING;
  69. stateChanged();
  70. download();
  71. }
  72.  
  73. // Cancel this download.
  74. public void cancel() {
  75. status = CANCELLED;
  76. stateChanged();
  77. }
  78.  
  79. // Mark this download as having an error.
  80. private void error() {
  81. status = ERROR;
  82. stateChanged();
  83. }
  84.  
  85. // Start or resume downloading.
  86. private void download() {
  87. Thread thread = new Thread(this);
  88. thread.start();
  89. }
  90.  
  91. // Get file name portion of URL.
  92. private String getFileName(URL url) {
  93. String fileName = url.getFile();
  94. return fileName.substring(fileName.lastIndexOf('/') + 1);
  95. }
  96.  
  97. // Download file.
  98. public void run() {
  99. RandomAccessFile file = null;
  100. InputStream stream = null;
  101.  
  102. try {
  103. // Open connection to URL.
  104. HttpURLConnection connection =
  105. (HttpURLConnection) url.openConnection();
  106.  
  107. // Specify what portion of file to download.
  108. connection.setRequestProperty("Range",
  109. "bytes=" + downloaded + "-");
  110.  
  111. // Connect to server.
  112. connection.connect();
  113.  
  114. // Make sure response code is in the 200 range.
  115. if (connection.getResponseCode() / 100 != 2) {
  116. error();
  117. }
  118.  
  119. // Check for valid content length.
  120. int contentLength = connection.getContentLength();
  121. if (contentLength < 1) {
  122. error();
  123. }
  124.  
  125. /* Set the size for this download if it
  126.   hasn't been already set. */
  127. if (size == -1) {
  128. size = contentLength;
  129. stateChanged();
  130. }
  131.  
  132. // Open file and seek to the end of it.
  133. file = new RandomAccessFile(getFileName(url), "rw");
  134. file.seek(downloaded);
  135.  
  136. stream = connection.getInputStream();
  137. while (status == DOWNLOADING) {
  138. /* Size buffer according to how much of the
  139.   file is left to download. */
  140. byte buffer[];
  141. if (size - downloaded > MAX_BUFFER_SIZE) {
  142. buffer = new byte[MAX_BUFFER_SIZE];
  143. } else {
  144. buffer = new byte[size - downloaded];
  145. }
  146.  
  147. // Read from server into buffer.
  148. int read = stream.read(buffer);
  149. if (read == -1)
  150. break;
  151.  
  152. // Write buffer to file.
  153. file.write(buffer, 0, read);
  154. downloaded += read;
  155. stateChanged();
  156. }
  157.  
  158. /* Change status to complete if this point was
  159.   reached because downloading has finished. */
  160. if (status == DOWNLOADING) {
  161. status = COMPLETE;
  162. stateChanged();
  163. }
  164. } catch (Exception e) {
  165. error();
  166. } finally {
  167. // Close file.
  168. if (file != null) {
  169. try {
  170. file.close();
  171. } catch (Exception e) {}
  172. }
  173.  
  174. // Close connection to server.
  175. if (stream != null) {
  176. try {
  177. stream.close();
  178. } catch (Exception e) {}
  179. }
  180. }
  181. }
  182.  
  183. // Notify observers that this download's status has changed.
  184. private void stateChanged() {
  185. setChanged();
  186. notifyObservers();
  187. }
  188.  
  189. public static void main(String args[]){
  190. try {
  191. Download d = new Download(new URL("http://hiphotos.baidu.com/happy_51qq/pic/item/1fec21c589a7108c8326ac9b.jpg"));
  192. d.run();
  193. } catch (MalformedURLException e) {
  194. // TODO Auto-generated catch block
  195. e.printStackTrace();
  196. }
  197. }
  198. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.