Merge branch 'master' of ssh://repo.or.cz/srv/git/simpleHTTP
[simpleHTTP.git] / src / eu / cepl / util / SimpleHTTP.java
blob86dafe7995e0b381188b7713cf4a9aadb810a46e
1 package eu.cepl.util;
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.StringBufferInputStream;
15 import java.io.UnsupportedEncodingException;
16 import java.net.MalformedURLException;
17 import java.net.URL;
18 import java.net.URLConnection;
19 import java.net.URLEncoder;
20 import java.util.HashMap;
21 import java.util.Map;
22 import java.util.Map.Entry;
24 public class SimpleHTTP {
26 private URL url = null;
27 private BufferedInputStream inBS = null;
28 private BufferedOutputStream outBS = null;
29 // private ConsoleHandler hand = new ConsoleHandler();
30 private URLConnection conn = null;
31 private URLConnection connection;
33 final static int BUFMAX = 1024;
35 // private static Logger logger =
36 // Logger.getLogger(SimpleHTTP.class.getName());
37 /**
41 public SimpleHTTP() {
42 // logger.addHandler(hand);
43 // hand.setFormatter(new ReallySimpleFormatter());
45 // if (new Boolean(System.getProperty("debugging"))) {
46 // hand.setLevel(Level.FINE);
47 // logger.setLevel(Level.FINE);
48 // } else {
49 // hand.setLevel(Level.INFO);
50 // logger.setLevel(Level.INFO);
51 // }
54 /**
56 * @param inURL
58 public SimpleHTTP(URL inURL) {
59 init(inURL);
62 /**
64 * @param strURL
65 * @throws MalformedURLException
67 public SimpleHTTP(String strURL) throws MalformedURLException {
68 init(new URL(strURL));
71 /**
73 * @param initURL
75 private void init(URL initURL) {
76 url = initURL;
79 /**
81 * @return
83 public URL getUrl() {
84 return url;
87 /**
89 * @param headers
90 * @return
91 * @throws IOException
93 private URLConnection getConnection(Map<String, String> headers)
94 throws IOException {
95 if (headers == null) {
96 headers = new HashMap<String, String>();
98 if (conn == null) {
99 conn = url.openConnection();
100 for (Entry<String, String> e : headers.entrySet()) {
101 conn.addRequestProperty(e.getKey(), e.getValue());
104 return conn;
109 * @param headers
110 * @return
111 * @throws IOException
113 public BufferedOutputStream getWriter(Map<String, String> headers)
114 throws IOException {
115 try {
116 connection = getConnection(headers);
117 connection.setDoOutput(true);
118 outBS = new BufferedOutputStream(connection.getOutputStream());
119 } catch (UnsupportedEncodingException e) {
120 // Cannot happen, UTF-8 is correct.
121 } catch (IOException e) {
122 throw new IOException("Cannot read from the HTTP command results.",
125 return outBS;
129 * Provides BufferedInputStream pointing to the URL.
131 * @param headers
132 * @return
133 * @throws IOException
135 public BufferedInputStream getReader(Map<String, String> headers)
136 throws IOException {
137 try {
138 connection = getConnection(headers);
139 inBS = new BufferedInputStream(connection.getInputStream());
140 } catch (IOException e) {
141 System.err.println("Cannot create BufferedInputStream for URL "
142 + url.toString());
143 e.printStackTrace();
144 throw e;
146 return inBS;
150 * reads whole stream into string
152 * @param in
153 * incoming byte stream
154 * @return String in UTF-8 encoding
155 * @throws IOException
157 public String suck(BufferedInputStream in) throws IOException {
159 StringBuffer inS = new StringBuffer();
160 InputStreamReader inR = null;
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 ((inR.read(cbuf)) != -1) {
169 inS.append(cbuf);
172 return inS.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 = getReader(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 data
210 * @param headers
211 * @return
212 * @throws IOException
214 @SuppressWarnings("unused")
215 public BufferedInputStream post(BufferedInputStream inStream,
216 Map<String, String> headers, String mime) throws IOException {
218 BufferedOutputStream outCh;
219 BufferedInputStream inCh;
220 long inLen = 0;
221 int c = 0;
222 byte[] inBuf = new byte[BUFMAX];
223 String mimeType = "";
225 if (mime == null) {
226 mimeType = "application/octet-stream";
227 } else {
228 mimeType = mime;
231 if (headers == null) {
232 headers = new HashMap<String, String>();
235 if (inLen > 0) {
236 headers.put("Content-Type", mimeType);
237 headers.put("Content-Length", Long.toString(inLen));
240 try {
241 outCh = getWriter(headers);
242 while ((c = inStream.read(inBuf)) != -1) {
243 outCh.write(inBuf);
245 outCh.flush();
246 outCh.close();
247 } catch (IOException e) {
248 throw new IOException("Cannot POST to URL " + url.toString(), e);
251 try {
252 inCh = getReader(null);
253 } catch (IOException e) {
254 throw new IOException("Cannot create Reader for URL "
255 + url.toString(), e);
258 return inCh;
262 * The main POST method for the object, expected to be used most. Both
263 * accepts data as String and returnes back String as a result.
265 * @param data
266 * String with data to be sent in the body of POST
267 * @param headers
268 * Map with pairs of String ... name of the header and the value
269 * of the header.
270 * @return String with the result of the calling POST
271 * @throws IOException
273 public String post(String data, Map<String, String> headers)
274 throws IOException {
276 return suck(post(new BufferedInputStream(new ByteArrayInputStream(
277 data.getBytes("UTF-8"))), headers,
278 "application/x-www-form-urlencoded"));
283 * @param inDict
284 * @param headers
285 * @return
286 * @throws IOException
288 public String post(Map<String, String> inDict, Map<String, String> headers)
289 throws IOException {
290 String strData = "";
292 for (Entry<String, String> e : inDict.entrySet()) {
293 try {
294 strData += URLEncoder.encode(e.getKey(), "UTF-8") + "="
295 + URLEncoder.encode(e.getValue(), "UTF-8") + "&";
296 } catch (UnsupportedEncodingException e1) {
297 // Never happens, UTF-8 is always supported
300 if (strData.charAt(strData.length() - 1) == '&') {
301 strData = strData.substring(0, strData.length() - 1);
303 return post(strData, headers);
308 * @param inData
309 * @return
310 * @throws IOException
312 public String post(String inData) throws IOException {
313 return post(inData, null);
318 * @param inDict
319 * @return
320 * @throws IOException
322 public String post(Map<String, String> inDict) throws IOException {
323 return post(inDict, null);