Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

Downloader.java 6.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195
  1. /*
  2. * Copyright (c) 2006-2014 DMDirc Developers
  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.io;
  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.URL;
  32. import java.net.URLConnection;
  33. import java.net.URLEncoder;
  34. import java.util.ArrayList;
  35. import java.util.List;
  36. import java.util.Map;
  37. /**
  38. * Allows easy downloading of files from HTTP sites.
  39. */
  40. public class Downloader {
  41. /**
  42. * Retrieves the specified page.
  43. *
  44. * @param url The URL to retrieve
  45. * @return A list of lines received from the server
  46. * @throws java.io.IOException If there's an I/O error while downloading
  47. */
  48. public List<String> getPage(final String url) throws IOException {
  49. return getPage(url, "");
  50. }
  51. /**
  52. * Retrieves the specified page, sending the specified post data.
  53. *
  54. * @param url The URL to retrieve
  55. * @param postData The raw POST data to send
  56. * @return A list of lines received from the server
  57. * @throws java.io.IOException If there's an I/O error while downloading
  58. */
  59. public List<String> getPage(final String url, final String postData)
  60. throws IOException {
  61. final List<String> res = new ArrayList<>();
  62. final URLConnection urlConn = getConnection(url, postData);
  63. try (BufferedReader in = new BufferedReader(new InputStreamReader(
  64. urlConn.getInputStream()))) {
  65. String line;
  66. do {
  67. line = in.readLine();
  68. if (line != null) {
  69. res.add(line);
  70. }
  71. } while (line != null);
  72. }
  73. return res;
  74. }
  75. /**
  76. * Retrieves the specified page, sending the specified post data.
  77. *
  78. * @param url The URL to retrieve
  79. * @param postData A map of post data that should be sent
  80. * @return A list of lines received from the server
  81. * @throws java.io.IOException If there's an I/O error while downloading
  82. */
  83. public List<String> getPage(final String url,
  84. final Map<String, String> postData) throws IOException {
  85. final StringBuilder data = new StringBuilder();
  86. for (Map.Entry<String, String> entry : postData.entrySet()) {
  87. data.append('&');
  88. data.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
  89. data.append('=');
  90. data.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
  91. }
  92. return getPage(url, data.length() == 0 ? "" : data.substring(1));
  93. }
  94. /**
  95. * Downloads the specified page to disk.
  96. *
  97. * @param url The URL to retrieve
  98. * @param file The file to save the page to
  99. * @throws java.io.IOException If there's an I/O error while downloading
  100. */
  101. public void downloadPage(final String url, final String file)
  102. throws IOException {
  103. downloadPage(url, file, null);
  104. }
  105. /**
  106. * Downloads the specified page to disk.
  107. *
  108. * @param url The URL to retrieve
  109. * @param file The file to save the page to
  110. * @param listener The progress listener for this download
  111. * @throws java.io.IOException If there's an I/O error while downloading
  112. */
  113. public void downloadPage(final String url, final String file,
  114. final DownloadListener listener) throws IOException {
  115. final URLConnection urlConn = getConnection(url, "");
  116. final File myFile = new File(file);
  117. try (OutputStream output = new FileOutputStream(myFile);
  118. InputStream input = urlConn.getInputStream()) {
  119. final int length = urlConn.getContentLength();
  120. int current = 0;
  121. if (listener != null) {
  122. listener.setIndeterminate(length == -1);
  123. }
  124. final byte[] buffer = new byte[512];
  125. int count;
  126. do {
  127. count = input.read(buffer);
  128. if (count > 0) {
  129. current += count;
  130. output.write(buffer, 0, count);
  131. if (listener != null && length != -1) {
  132. listener.downloadProgress(100 * (float) current
  133. / length);
  134. }
  135. }
  136. } while (count > 0);
  137. }
  138. }
  139. /**
  140. * Creates an URL connection for the specified URL and data.
  141. *
  142. * @param url The URL to connect to
  143. * @param postData The POST data to pass to the URL
  144. * @return An URLConnection for the specified URL/data
  145. * @throws java.io.IOException If an I/O exception occurs while connecting
  146. */
  147. private URLConnection getConnection(final String url,
  148. final String postData)
  149. throws IOException {
  150. final URL myUrl = new URL(url);
  151. final URLConnection urlConn = myUrl.openConnection();
  152. urlConn.setUseCaches(false);
  153. urlConn.setDoInput(true);
  154. urlConn.setDoOutput(!postData.isEmpty());
  155. urlConn.setConnectTimeout(10000);
  156. if (!postData.isEmpty()) {
  157. urlConn.setRequestProperty("Content-Type",
  158. "application/x-www-form-urlencoded");
  159. try (DataOutputStream out = new DataOutputStream(urlConn.getOutputStream())) {
  160. out.writeBytes(postData);
  161. out.flush();
  162. }
  163. }
  164. return urlConn;
  165. }
  166. }