1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 package org.xnap.net;
21
22 import java.io.BufferedReader;
23 import java.io.IOException;
24 import java.io.InputStream;
25 import java.io.InputStreamReader;
26 import java.net.HttpURLConnection;
27 import java.net.URL;
28
29 /***
30 * This class provides a convenience wrapper for the
31 * {@link java.net.HttpURLConnection} class.
32 */
33 public class HttpConnection {
34
35
36
37 private BufferedReader in = null;
38 private HttpURLConnection connection = null;
39
40
41
42 /***
43 * Constructs a http connection. No action is taken.
44 */
45 public HttpConnection()
46 {
47 }
48
49
50
51 /***
52 * Establishes a connection to <code>url</code>.
53 *
54 * @param url the url to connect to
55 * @exception IOException thrown if the connection fails
56 */
57 public void connect(URL url) throws IOException
58 {
59 connection = (HttpURLConnection)url.openConnection();
60 if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
61 in = new BufferedReader
62 (new InputStreamReader(connection.getInputStream()));
63
64 }
65 else {
66 connection.disconnect();
67 throw new IOException(connection.getResponseMessage());
68 }
69 }
70
71 /***
72 * Establishes a connection to <code>location</code>.
73 *
74 * @param location the url to connect to
75 * @exception IOException thrown if the connection fails
76 */
77 public void connect(String location) throws IOException
78 {
79 connect(new URL(location));
80 }
81
82 /***
83 * Closes the connection.
84 */
85 public void close()
86 {
87 connection.disconnect();
88 }
89
90 /***
91 * Returns the associated input stream. The connection needs to be
92 * established prior to invoking this method.
93 *
94 * @see #connect(URL)
95 */
96 public InputStream getInputStream() throws IOException
97 {
98 return connection.getInputStream();
99 }
100
101 /***
102 * Reads and returns the next line from the input stream. The connection
103 * is automatically closed if the end of the stream is reached.
104 *
105 * @return null, if the end of the stream is reached or an exception
106 * occurs
107 */
108 public String nextLine()
109 {
110 if (in == null) {
111 return null;
112 }
113
114 String line = null;
115 try {
116 line = in.readLine();
117 }
118 catch(IOException e) {
119 }
120
121 if (line == null) {
122 connection.disconnect();
123 }
124
125 return line;
126 }
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143 }