FetchURL.java 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. package com.ivalentin.gm;
  2. import java.io.BufferedReader;
  3. import java.io.InputStreamReader;
  4. import java.net.URL;
  5. import java.util.ArrayList;
  6. import java.util.List;
  7. /**
  8. * Class that fetches an online page.
  9. *
  10. * @author Inigo Valentin
  11. *
  12. */
  13. public class FetchURL {
  14. //List of strings that will contain the output, line by line
  15. private List<String> output;
  16. private String url;
  17. /**
  18. * Constructor.
  19. */
  20. public FetchURL(){
  21. output = new ArrayList<>();
  22. }
  23. /**
  24. * Returns the content of the fetched page.
  25. *
  26. * @return A List of strings containing the lines of the web page.
  27. */
  28. public List<String> getOutput(){
  29. return output;
  30. }
  31. /**
  32. * Actually fetches the web page.
  33. *
  34. * @param u The URL to fetch.
  35. */
  36. public void Run(String u){
  37. url = u;
  38. Thread t = new Thread() {
  39. public void run() {
  40. URL textUrl;
  41. try {
  42. textUrl = new URL(url);
  43. BufferedReader bufferReader = new BufferedReader(new InputStreamReader(textUrl.openStream()));
  44. String StringBuffer;
  45. List<String> lines = new ArrayList<>();
  46. while ((StringBuffer = bufferReader.readLine()) != null) {
  47. lines.add(StringBuffer);
  48. }
  49. bufferReader.close();
  50. output = lines;
  51. }
  52. catch (Exception e) {
  53. e.printStackTrace();
  54. output.add(e.toString());
  55. }
  56. }
  57. };
  58. t.start();
  59. try {
  60. t.join();
  61. }
  62. catch (InterruptedException e) {
  63. e.printStackTrace();
  64. }
  65. }
  66. }