View Javadoc
1   package auxtestlib;
2   
3   import java.io.ByteArrayOutputStream;
4   import java.io.IOException;
5   import java.io.InputStream;
6   import java.io.InputStreamReader;
7   import java.net.URL;
8   
9   /**
10   * Class that obtains data from the web. Code initially copied (and later
11   * changed) from http://www.devdaily.com/blog/post/java/jget-something-like-wget
12   */
13  public final class WebGetter {
14  	/**
15  	 * Utility class: no constructor.
16  	 */
17  	private WebGetter() {
18  		/*
19  		 * Nothing to do.
20  		 */
21  	}
22  
23  	/**
24  	 * Obtains a URL as binary data.
25  	 * 
26  	 * @param url the URL
27  	 * 
28  	 * @return the data
29  	 * 
30  	 * @throws Exception failed to obtain the data
31  	 */
32  	public static byte[] getBinary(String url) throws Exception {
33  		URL u;
34  		int b;
35  		InputStream is = null;
36  		ByteArrayOutputStream os = new ByteArrayOutputStream();
37  
38  		try {
39  			u = new URL(url);
40  			is = u.openStream();
41  			while ((b = is.read()) != -1) {
42  				os.write(b);
43  			}
44  
45  			is.close();
46  			is = null;
47  		} finally {
48  			if (is != null) {
49  				try {
50  					is.close();
51  				} catch (IOException ioe) {
52  					/*
53  					 * Double exception: ignore.
54  					 */
55  				}
56  			}
57  		}
58  
59  		return os.toByteArray();
60  	}
61  
62  	/**
63  	 * Obtains the text at a given URL.
64  	 * 
65  	 * @param url the URL to retrieve
66  	 * 
67  	 * @return the URL's text
68  	 * 
69  	 * @throws Exception failed to obtain the text at the URL
70  	 */
71  	public static String get(String url) throws Exception {
72  		URL u;
73  		int c;
74  		InputStream is = null;
75  		InputStreamReader isr = null;
76  		StringBuffer sb = new StringBuffer();
77  
78  		try {
79  			u = new URL(url);
80  			is = u.openStream();
81  			isr = new InputStreamReader(is);
82  			while ((c = isr.read()) != -1) {
83  				sb.append((char) c);
84  			}
85  
86  			is.close();
87  			is = null;
88  			isr.close();
89  			isr = null;
90  		} finally {
91  			if (is != null) {
92  				try {
93  					is.close();
94  				} catch (IOException ioe) {
95  					/*
96  					 * Double exception: ignore.
97  					 */
98  				}
99  			}
100 
101 			if (isr != null) {
102 				try {
103 					isr.close();
104 				} catch (IOException ioe) {
105 					/*
106 					 * Double exception: ignore.
107 					 */
108 				}
109 			}
110 		}
111 
112 		return sb.toString();
113 	}
114 }