Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228
  1. /*
  2. * Copyright (c) 2006-2011 Chris Smith, Shane Mc Cormack, Gregory Holmes
  3. *
  4. * Permission is hereby granted, free of charge, to any person obtaining a copy
  5. * of this software and associated documentation files (the "Software"), to deal
  6. * in the Software without restriction, including without limitation the rights
  7. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. * copies of the Software, and to permit persons to whom the Software is
  9. * furnished to do so, subject to the following conditions:
  10. *
  11. * The above copyright notice and this permission notice shall be included in
  12. * all copies or substantial portions of the Software.
  13. *
  14. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  20. * SOFTWARE.
  21. */
  22. package com.dmdirc.util;
  23. import java.io.BufferedReader;
  24. import java.io.DataOutputStream;
  25. import java.io.File;
  26. import java.io.FileOutputStream;
  27. import java.io.IOException;
  28. import java.io.InputStream;
  29. import java.io.InputStreamReader;
  30. import java.io.OutputStream;
  31. import java.net.MalformedURLException;
  32. import java.net.URL;
  33. import java.net.URLConnection;
  34. import java.net.URLEncoder;
  35. import java.util.ArrayList;
  36. import java.util.List;
  37. import java.util.Map;
  38. /**
  39. * Allows easy downloading of files from HTTP sites.
  40. *
  41. * @author Chris
  42. */
  43. public final class Downloader {
  44. /** Creates a new instance of Downloader. */
  45. private Downloader() {
  46. // Shouldn't be used
  47. }
  48. /**
  49. * Retrieves the specified page.
  50. *
  51. * @param url The URL to retrieve
  52. * @return A list of lines received from the server
  53. * @throws java.net.MalformedURLException If the URL is malformed
  54. * @throws java.io.IOException If there's an I/O error while downloading
  55. */
  56. public static List<String> getPage(final String url)
  57. throws MalformedURLException, IOException {
  58. return getPage(url, "");
  59. }
  60. /**
  61. * Retrieves the specified page, sending the specified post data.
  62. *
  63. * @param url The URL to retrieve
  64. * @param postData The raw POST data to send
  65. * @return A list of lines received from the server
  66. * @throws java.net.MalformedURLException If the URL is malformed
  67. * @throws java.io.IOException If there's an I/O error while downloading
  68. */
  69. public static List<String> getPage(final String url, final String postData)
  70. throws MalformedURLException, IOException {
  71. final List<String> res = new ArrayList<String>();
  72. final URLConnection urlConn = getConnection(url, postData);
  73. BufferedReader in = null;
  74. try {
  75. in = new BufferedReader(new InputStreamReader(
  76. urlConn.getInputStream()));
  77. String line;
  78. do {
  79. line = in.readLine();
  80. if (line != null) {
  81. res.add(line);
  82. }
  83. } while (line != null);
  84. } finally {
  85. StreamUtil.close(in);
  86. }
  87. return res;
  88. }
  89. /**
  90. * Retrieves the specified page, sending the specified post data.
  91. *
  92. * @param url The URL to retrieve
  93. * @param postData A map of post data that should be sent
  94. * @return A list of lines received from the server
  95. * @throws java.net.MalformedURLException If the URL is malformed
  96. * @throws java.io.IOException If there's an I/O error while downloading
  97. */
  98. public static List<String> getPage(final String url,
  99. final Map<String, String> postData)
  100. throws MalformedURLException, IOException {
  101. final StringBuilder data = new StringBuilder();
  102. for (Map.Entry<String, String> entry : postData.entrySet()) {
  103. data.append('&');
  104. data.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
  105. data.append('=');
  106. data.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
  107. }
  108. return getPage(url, data.length() == 0 ? "" : data.substring(1));
  109. }
  110. /**
  111. * Downloads the specified page to disk.
  112. *
  113. * @param url The URL to retrieve
  114. * @param file The file to save the page to
  115. * @throws java.io.IOException If there's an I/O error while downloading
  116. */
  117. public static void downloadPage(final String url, final String file)
  118. throws IOException {
  119. downloadPage(url, file, null);
  120. }
  121. /**
  122. * Downloads the specified page to disk.
  123. *
  124. * @param url The URL to retrieve
  125. * @param file The file to save the page to
  126. * @param listener The progress listener for this download
  127. * @throws java.io.IOException If there's an I/O error while downloading
  128. */
  129. public static void downloadPage(final String url, final String file,
  130. final DownloadListener listener) throws IOException {
  131. final URLConnection urlConn = getConnection(url, "");
  132. final File myFile = new File(file);
  133. OutputStream output = null;
  134. InputStream input = null;
  135. try {
  136. output = new FileOutputStream(myFile);
  137. input = urlConn.getInputStream();
  138. final int length = urlConn.getContentLength();
  139. int current = 0;
  140. if (listener != null) {
  141. listener.setIndeterminate(length == -1);
  142. }
  143. final byte[] buffer = new byte[512];
  144. int count;
  145. do {
  146. count = input.read(buffer);
  147. if (count > 0) {
  148. current += count;
  149. output.write(buffer, 0, count);
  150. if (listener != null && length != -1) {
  151. listener.downloadProgress(100 * (float) current
  152. / length);
  153. }
  154. }
  155. } while (count > 0);
  156. } finally {
  157. StreamUtil.close(input);
  158. StreamUtil.close(output);
  159. }
  160. }
  161. /**
  162. * Creates an URL connection for the specified URL and data.
  163. *
  164. * @param url The URL to connect to
  165. * @param postData The POST data to pass to the URL
  166. * @return An URLConnection for the specified URL/data
  167. * @throws java.net.MalformedURLException If the specified URL is malformed
  168. * @throws java.io.IOException If an I/O exception occurs while connecting
  169. */
  170. private static URLConnection getConnection(final String url,
  171. final String postData)
  172. throws MalformedURLException, IOException {
  173. final URL myUrl = new URL(url);
  174. final URLConnection urlConn = myUrl.openConnection();
  175. urlConn.setUseCaches(false);
  176. urlConn.setDoInput(true);
  177. urlConn.setDoOutput(postData.length() > 0);
  178. urlConn.setConnectTimeout(10000);
  179. if (postData.length() > 0) {
  180. urlConn.setRequestProperty("Content-Type",
  181. "application/x-www-form-urlencoded");
  182. DataOutputStream out = null;
  183. try {
  184. out = new DataOutputStream(urlConn.getOutputStream());
  185. out.writeBytes(postData);
  186. out.flush();
  187. } finally {
  188. StreamUtil.close(out);
  189. }
  190. }
  191. return urlConn;
  192. }
  193. }