Adding and completing tests with testurl.
[simpleHTTP.git] / src / eu / cepl / network / SimpleHTTP.java
blob4501c02173a779e4a086965c9d59e57c86c8523a
1 package eu.cepl.network;
3 /*
4 * TODO:
5 * - I have to figure out how to switch on logging for HTTP protocol
6 * - Location:
7 * - Cookies!
8 */
9 import java.io.BufferedInputStream;
10 import java.io.BufferedOutputStream;
11 import java.io.ByteArrayInputStream;
12 import java.io.IOException;
13 import java.io.InputStreamReader;
14 import java.io.UnsupportedEncodingException;
15 import java.net.MalformedURLException;
16 import java.net.URL;
17 import java.net.URLConnection;
18 import java.net.URLEncoder;
19 import java.util.HashMap;
20 import java.util.Map;
21 import java.util.Map.Entry;
23 public class SimpleHTTP {
25 private URL url = null;
26 private BufferedInputStream inBS = null;
27 private BufferedOutputStream outBS = null;
28 // private ConsoleHandler hand = new ConsoleHandler();
29 private URLConnection conn = null;
30 private URLConnection connection;
32 final static int BUFMAX = 1024;
34 // private static Logger logger =
35 // Logger.getLogger(SimpleHTTP.class.getName());
36 /**
40 public SimpleHTTP() {
41 // logger.addHandler(hand);
42 // hand.setFormatter(new ReallySimpleFormatter());
44 // if (new Boolean(System.getProperty("debugging"))) {
45 // hand.setLevel(Level.FINE);
46 // logger.setLevel(Level.FINE);
47 // } else {
48 // hand.setLevel(Level.INFO);
49 // logger.setLevel(Level.INFO);
50 // }
53 /**
55 * @param inURL
57 public SimpleHTTP(URL inURL) {
58 init(inURL);
61 /**
63 * @param strURL
64 * @throws MalformedURLException
66 public SimpleHTTP(String strURL) throws MalformedURLException {
67 init(new URL(strURL));
70 /**
72 * @param initURL
74 private void init(URL initURL) {
75 url = initURL;
78 /**
80 * @return
82 public URL getUrl() {
83 return url;
86 /**
88 * @param headers
89 * @return
90 * @throws IOException
92 private URLConnection getConnection(Map<String, String> headers)
93 throws IOException {
94 if (headers == null) {
95 headers = new HashMap<String, String>();
97 if (conn == null) {
98 conn = url.openConnection();
99 for (Entry<String, String> e : headers.entrySet()) {
100 conn.addRequestProperty(e.getKey(), e.getValue());
103 return conn;
108 * @param headers
109 * @return
110 * @throws IOException
112 public BufferedOutputStream getWriter(Map<String, String> headers)
113 throws IOException {
114 try {
115 connection = getConnection(headers);
116 connection.setDoOutput(true);
117 outBS = new BufferedOutputStream(connection.getOutputStream());
118 } catch (UnsupportedEncodingException e) {
119 // Cannot happen, UTF-8 is correct.
120 } catch (IOException e) {
121 throw new IOException("Cannot read from the HTTP command results.",
124 return outBS;
128 * Provides BufferedInputStream pointing to the URL.
130 * @param headers
131 * @return
132 * @throws IOException
134 public BufferedInputStream getInputStream(Map<String, String> headers)
135 throws IOException {
136 try {
137 connection = getConnection(headers);
138 inBS = new BufferedInputStream(connection.getInputStream());
139 } catch (IOException e) {
140 System.err.println("Cannot create BufferedInputStream for URL "
141 + url.toString());
142 e.printStackTrace();
143 throw e;
145 return inBS;
149 * reads whole stream into string
151 * @param in
152 * incoming byte stream
153 * @return String in UTF-8 encoding
154 * @throws IOException
156 String suck(BufferedInputStream in) throws IOException {
157 StringBuffer inBuf = new StringBuffer();
158 InputStreamReader inR = null;
159 int count = 0;
161 try {
162 inR = new InputStreamReader(in, "UTF-8");
163 } catch (UnsupportedEncodingException e) {
164 // Cannot happen, UTF-8 is always supported
166 char[] cbuf = new char[BUFMAX];
168 while ((count = inR.read(cbuf)) != -1) {
169 inBuf.append(cbuf, 0, count);
172 return inBuf.toString();
177 * @param headers
178 * @return
179 * @throws IOException
181 public String get(Map<String, String> headers) throws IOException {
182 BufferedInputStream inCh;
184 if (headers == null) {
185 headers = new HashMap<String, String>();
188 try {
189 inCh = getInputStream(headers);
190 } catch (IOException e) {
191 throw new IOException("Cannot create Reader for URL "
192 + url.toString(), e);
195 return suck(inCh);
200 * @return
201 * @throws IOException
203 public String get() throws IOException {
204 return get(null);
209 * @param inStream
210 * @param headers
211 * @param mime String with MIME type of data in {@literal inStream}
212 * @return BufferedInputStream with the data returned from the server
213 * @throws IOException
215 @SuppressWarnings("unused")
216 public BufferedInputStream post(BufferedInputStream inStream,
217 Map<String, String> headers, String mime) throws IOException {
219 BufferedOutputStream outCh;
220 BufferedInputStream inCh;
221 long inLen = 0;
222 int c = 0;
223 byte[] inBuf = new byte[BUFMAX];
224 String mimeType = "";
226 if (mime == null) {
227 mimeType = "application/octet-stream";
228 } else {
229 mimeType = mime;
232 if (headers == null) {
233 headers = new HashMap<String, String>();
236 if (inLen > 0) {
237 headers.put("Content-Type", mimeType);
238 headers.put("Content-Length", Long.toString(inLen));
241 try {
242 outCh = getWriter(headers);
243 while ((c = inStream.read(inBuf)) != -1) {
244 outCh.write(inBuf);
246 outCh.flush();
247 outCh.close();
248 } catch (IOException e) {
249 throw new IOException("Cannot POST to URL " + url.toString(), e);
252 try {
253 inCh = getInputStream(null);
254 } catch (IOException e) {
255 throw new IOException("Cannot create Reader for URL "
256 + url.toString(), e);
259 return inCh;
263 * The main POST method for the object, expected to be used most. Both
264 * accepts data as String and returnes back String as a result.
266 * @param data
267 * String with data to be sent in the body of POST
268 * @param headers
269 * Map with pairs of String ... name of the header and the value
270 * of the header.
271 * @return String with the result of the calling POST
272 * @throws IOException
274 public String post(String data, Map<String, String> headers)
275 throws IOException {
277 return suck(post(new BufferedInputStream(new ByteArrayInputStream(
278 data.getBytes("UTF-8"))), headers,
279 "application/x-www-form-urlencoded"));
284 * @param inDict
285 * @param headers
286 * @return
287 * @throws IOException
289 public String post(Map<String, String> inDict, Map<String, String> headers)
290 throws IOException {
291 String strData = "";
293 for (Entry<String, String> e : inDict.entrySet()) {
294 try {
295 strData += URLEncoder.encode(e.getKey(), "UTF-8") + "="
296 + URLEncoder.encode(e.getValue(), "UTF-8") + "&";
297 } catch (UnsupportedEncodingException e1) {
298 // Never happens, UTF-8 is always supported
301 if (strData.charAt(strData.length() - 1) == '&') {
302 strData = strData.substring(0, strData.length() - 1);
304 return post(strData, headers);
309 * @param inData
310 * @return
311 * @throws IOException
313 public String post(String inData) throws IOException {
314 return post(inData, null);
319 * @param inDict
320 * @return
321 * @throws IOException
323 public String post(Map<String, String> inDict) throws IOException {
324 return post(inDict, null);