KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > infoglue > deliver > util > HttpHelper


1 /* ===============================================================================
2  *
3  * Part of the InfoGlue Content Management Platform (www.infoglue.org)
4  *
5  * ===============================================================================
6  *
7  * Copyright (C)
8  *
9  * This program is free software; you can redistribute it and/or modify it under
10  * the terms of the GNU General Public License version 2, as published by the
11  * Free Software Foundation. See the file LICENSE.html for more information.
12  *
13  * This program is distributed in the hope that it will be useful, but WITHOUT
14  * ANY WARRANTY, including the implied warranty of MERCHANTABILITY or FITNESS
15  * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License along with
18  * this program; if not, write to the Free Software Foundation, Inc. / 59 Temple
19  * Place, Suite 330 / Boston, MA 02111-1307 / USA.
20  *
21  * ===============================================================================
22  */

23
24 package org.infoglue.deliver.util;
25
26 import java.io.BufferedReader JavaDoc;
27 import java.io.BufferedWriter JavaDoc;
28 import java.io.ByteArrayOutputStream JavaDoc;
29 import java.io.InputStream JavaDoc;
30 import java.io.InputStreamReader JavaDoc;
31 import java.io.OutputStreamWriter JavaDoc;
32 import java.io.PrintWriter JavaDoc;
33 import java.net.URL JavaDoc;
34 import java.net.URLConnection JavaDoc;
35 import java.net.URLEncoder JavaDoc;
36 import java.util.Enumeration JavaDoc;
37 import java.util.Hashtable JavaDoc;
38 import java.util.Iterator JavaDoc;
39 import java.util.Map JavaDoc;
40
41 import javax.servlet.http.Cookie JavaDoc;
42 import javax.servlet.http.HttpServletRequest JavaDoc;
43
44 import org.apache.log4j.Logger;
45
46
47
48 /**
49  * @author Mattias Bogeblad
50  *
51  * Various methods to fetch url-contents
52  */

53
54 public class HttpHelper
55 {
56     private final static Logger logger = Logger.getLogger(HttpHelper.class.getName());
57
58     public String JavaDoc postToUrl(String JavaDoc urlAddress, HttpServletRequest JavaDoc request, boolean includeRequest) throws Exception JavaDoc
59     {
60         if(includeRequest)
61             return postToUrl(urlAddress, requestToHashtable(request), "UTF-8");
62         else
63             return postToUrl(urlAddress, new Hashtable JavaDoc(), "UTF-8");
64     }
65
66     public String JavaDoc postToUrl(String JavaDoc urlAddress, HttpServletRequest JavaDoc request, boolean includeRequest, String JavaDoc encoding) throws Exception JavaDoc
67     {
68         if(includeRequest)
69             return postToUrl(urlAddress, requestToHashtable(request), encoding);
70         else
71             return postToUrl(urlAddress, new Hashtable JavaDoc(), encoding);
72     }
73
74     /**
75      * This method post information to an URL and returns a string.It throws
76      * an exception if anything goes wrong.
77      * (Works like most 'doPost' methods)
78      *
79      * @param urlAddress The address of the URL you would like to post to.
80      * @param inHash The parameters you would like to post to the URL.
81      * @return The result of the postToUrl method as a string.
82      * @exception java.lang.Exception
83      */

84     
85     public String JavaDoc postToUrl(String JavaDoc urlAddress, Hashtable JavaDoc inHash, String JavaDoc encoding) throws Exception JavaDoc
86     {
87         URL JavaDoc url = new URL JavaDoc(urlAddress);
88         URLConnection JavaDoc urlConn = url.openConnection();
89         urlConn.setAllowUserInteraction(false);
90         urlConn.setDoOutput (true);
91         urlConn.setDoInput (true);
92         urlConn.setUseCaches (false);
93         urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
94         PrintWriter JavaDoc printout = new PrintWriter JavaDoc(urlConn.getOutputStream(), true);
95         String JavaDoc argString = "";
96         if(inHash != null)
97         {
98             argString = toEncodedString(inHash, encoding);
99         }
100         printout.print(argString);
101         printout.flush();
102         printout.close ();
103         InputStream JavaDoc inStream = null;
104         inStream = urlConn.getInputStream();
105         InputStreamReader JavaDoc inStreamReader = new InputStreamReader JavaDoc(inStream);
106         BufferedReader JavaDoc buffer = new BufferedReader JavaDoc(inStreamReader);
107         StringBuffer JavaDoc strbuf = new StringBuffer JavaDoc();
108         String JavaDoc line;
109         while((line = buffer.readLine()) != null)
110         {
111             strbuf.append(line);
112         }
113         String JavaDoc readData = strbuf.toString();
114         buffer.close();
115         return readData;
116     }
117
118
119     /**
120      * This method post information to an URL and returns a string.It throws
121      * an exception if anything goes wrong.
122      * (Works like most 'doPost' methods)
123      *
124      * @param urlAddress The address of the URL you would like to post to.
125      * @param inHash The parameters you would like to post to the URL.
126      * @return The result of the postToUrl method as a string.
127      * @exception java.lang.Exception
128      */

129     
130     public String JavaDoc postToUrl(String JavaDoc urlAddress, Hashtable JavaDoc inHash, String JavaDoc userName, String JavaDoc password, boolean shouldEncode) throws Exception JavaDoc
131     {
132         String JavaDoc encodedPassword = HTUU.encode(userName + ":" + password);
133         
134         URL JavaDoc url = new URL JavaDoc(urlAddress);
135         URLConnection JavaDoc urlConn = url.openConnection();
136         urlConn.setAllowUserInteraction(false);
137         urlConn.setDoOutput (true);
138         urlConn.setDoInput (true);
139         urlConn.setUseCaches (false);
140         urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
141         urlConn.setRequestProperty("Authorization", "Basic " + encodedPassword);
142         PrintWriter JavaDoc printout = new PrintWriter JavaDoc(urlConn.getOutputStream(), true);
143         String JavaDoc argString = "";
144         if(inHash != null)
145         {
146             if (shouldEncode)
147                 argString = toEncodedString(inHash, "UTF-8");
148             else
149                 argString = toString(inHash);
150         }
151         printout.print(argString);
152         printout.flush();
153         printout.close ();
154         InputStream JavaDoc inStream = null;
155         inStream = urlConn.getInputStream();
156         InputStreamReader JavaDoc inStreamReader = new InputStreamReader JavaDoc(inStream);
157         BufferedReader JavaDoc buffer = new BufferedReader JavaDoc(inStreamReader);
158         StringBuffer JavaDoc strbuf = new StringBuffer JavaDoc();
159         String JavaDoc line;
160         while((line = buffer.readLine()) != null)
161         {
162             strbuf.append(line);
163         }
164         String JavaDoc readData = strbuf.toString();
165         buffer.close();
166         return readData;
167     }
168
169      
170     public String JavaDoc getUrlContent(String JavaDoc urlAddress, HttpServletRequest JavaDoc request, boolean includeRequest) throws Exception JavaDoc
171     {
172         if(includeRequest)
173             return getUrlContent(urlAddress, requestToHashtable(request));
174         else
175             return getUrlContent(urlAddress);
176     }
177
178     public String JavaDoc getUrlContent(String JavaDoc urlAddress, HttpServletRequest JavaDoc request, boolean includeRequest, String JavaDoc encoding) throws Exception JavaDoc
179     {
180         if(includeRequest)
181             return getUrlContent(urlAddress, requestToHashtable(request), encoding);
182         else
183             return getUrlContent(urlAddress, encoding);
184     }
185
186     public String JavaDoc getUrlContent(String JavaDoc urlAddress, Hashtable JavaDoc inHash) throws Exception JavaDoc
187     {
188         String JavaDoc argString = "";
189         if(inHash != null)
190         {
191             if(urlAddress.indexOf("?") > -1)
192                 argString = "&" + toEncodedString(inHash, "UTF-8");
193             else
194                 argString = "?" + toEncodedString(inHash, "UTF-8");
195         }
196
197         logger.info("Getting content from url: " + urlAddress + argString);
198         
199         URL JavaDoc url = new URL JavaDoc(urlAddress + argString);
200         URLConnection JavaDoc connection = url.openConnection();
201         connection.setUseCaches(false);
202         InputStream JavaDoc inStream = null;
203         inStream = connection.getInputStream();
204         InputStreamReader JavaDoc inStreamReader = new InputStreamReader JavaDoc(inStream, "ISO-8859-1");
205         BufferedReader JavaDoc buffer = new BufferedReader JavaDoc(inStreamReader);
206         StringBuffer JavaDoc strbuf = new StringBuffer JavaDoc();
207         String JavaDoc line;
208         while((line = buffer.readLine()) != null)
209         {
210             strbuf.append(line);
211         }
212         String JavaDoc readData = strbuf.toString();
213         buffer.close();
214                                                 
215         return readData;
216     }
217
218
219     public String JavaDoc getUrlContent(String JavaDoc urlAddress, Hashtable JavaDoc inHash, String JavaDoc encoding) throws Exception JavaDoc
220     {
221         String JavaDoc argString = "";
222         if(inHash != null)
223         {
224             if(urlAddress.indexOf("?") > -1)
225                 argString = "&" + toEncodedString(inHash, encoding);
226             else
227                 argString = "?" + toEncodedString(inHash, encoding);
228         }
229
230         logger.info("Getting content from url: " + urlAddress + argString);
231         
232         URL JavaDoc url = new URL JavaDoc(urlAddress + argString);
233         URLConnection JavaDoc connection = url.openConnection();
234         connection.setUseCaches(false);
235         InputStream JavaDoc inStream = null;
236         inStream = connection.getInputStream();
237         InputStreamReader JavaDoc inStreamReader = new InputStreamReader JavaDoc(inStream, encoding);
238         BufferedReader JavaDoc buffer = new BufferedReader JavaDoc(inStreamReader);
239         StringBuffer JavaDoc strbuf = new StringBuffer JavaDoc();
240         String JavaDoc line;
241         while((line = buffer.readLine()) != null)
242         {
243             strbuf.append(line);
244         }
245         String JavaDoc readData = strbuf.toString();
246         buffer.close();
247
248         ByteArrayOutputStream JavaDoc baos = new ByteArrayOutputStream JavaDoc();
249         BufferedWriter JavaDoc writer = new BufferedWriter JavaDoc(new OutputStreamWriter JavaDoc(baos, "UTF-8"));
250         writer.write(readData);
251
252         baos.flush();
253         baos.close();
254         writer.flush();
255         writer.close();
256         
257         readData = new String JavaDoc(baos.toString(encoding));
258                                                 
259         return readData;
260     }
261
262     
263     public String JavaDoc getUrlContent(String JavaDoc urlAddress) throws Exception JavaDoc
264     {
265         URL JavaDoc url = new URL JavaDoc(urlAddress);
266         URLConnection JavaDoc connection = url.openConnection();
267         connection.setUseCaches(false);
268
269         InputStream JavaDoc inStream = null;
270         inStream = connection.getInputStream();
271         InputStreamReader JavaDoc inStreamReader = new InputStreamReader JavaDoc(inStream);
272         BufferedReader JavaDoc buffer = new BufferedReader JavaDoc(inStreamReader);
273         StringBuffer JavaDoc strbuf = new StringBuffer JavaDoc();
274         String JavaDoc line;
275         while((line = buffer.readLine()) != null)
276         {
277             strbuf.append(line);
278         }
279         String JavaDoc readData = strbuf.toString();
280         buffer.close();
281         return readData;
282     }
283     
284     public String JavaDoc getUrlContent(String JavaDoc urlAddress, Map JavaDoc requestParameters) throws Exception JavaDoc
285     {
286         URL JavaDoc url = new URL JavaDoc(urlAddress);
287         URLConnection JavaDoc connection = url.openConnection();
288         connection.setUseCaches(false);
289         
290         Iterator JavaDoc mapIterator = requestParameters.keySet().iterator();
291         while(mapIterator.hasNext())
292         {
293             String JavaDoc key = (String JavaDoc)mapIterator.next();
294             String JavaDoc value = (String JavaDoc)requestParameters.get(key);
295             connection.setRequestProperty(key, value);
296         }
297         
298         InputStream JavaDoc inStream = null;
299         inStream = connection.getInputStream();
300         InputStreamReader JavaDoc inStreamReader = new InputStreamReader JavaDoc(inStream);
301         BufferedReader JavaDoc buffer = new BufferedReader JavaDoc(inStreamReader);
302         StringBuffer JavaDoc strbuf = new StringBuffer JavaDoc();
303         String JavaDoc line;
304         while((line = buffer.readLine()) != null)
305         {
306             strbuf.append(line);
307         }
308         String JavaDoc readData = strbuf.toString();
309         buffer.close();
310         return readData;
311     }
312
313     public String JavaDoc getUrlContent(String JavaDoc urlAddress, String JavaDoc encoding) throws Exception JavaDoc
314     {
315         URL JavaDoc url = new URL JavaDoc(urlAddress);
316         URLConnection JavaDoc connection = url.openConnection();
317         connection.setUseCaches(false);
318         InputStream JavaDoc inStream = null;
319         inStream = connection.getInputStream();
320         InputStreamReader JavaDoc inStreamReader = new InputStreamReader JavaDoc(inStream, encoding);
321         BufferedReader JavaDoc buffer = new BufferedReader JavaDoc(inStreamReader);
322         StringBuffer JavaDoc strbuf = new StringBuffer JavaDoc();
323         String JavaDoc line;
324         while((line = buffer.readLine()) != null)
325         {
326             strbuf.append(line);
327         }
328         String JavaDoc readData = strbuf.toString();
329         buffer.close();
330         
331         ByteArrayOutputStream JavaDoc baos = new ByteArrayOutputStream JavaDoc();
332         BufferedWriter JavaDoc writer = new BufferedWriter JavaDoc(new OutputStreamWriter JavaDoc(baos, "UTF-8"));
333         writer.write(readData);
334
335         baos.flush();
336         baos.close();
337         writer.flush();
338         writer.close();
339
340         readData = new String JavaDoc(baos.toString(encoding));
341         
342         return readData;
343     }
344     
345     /**
346      * This method gets information form an URL and returns a string.It throws
347      * an exception if anything goes wrong.
348      * (Works like most 'doGet' methods)
349      *
350      * @param urlAddress The address of the URL you would like to get information from.
351      * @param inHash The parameters you would like to get from the URL.
352      * @return The result of the getUrlContent method as a string.
353      * @exception java.lang.Exception
354      */

355               
356     public String JavaDoc getUrlContent(String JavaDoc urlAddress, Hashtable JavaDoc inHash, String JavaDoc userName, String JavaDoc password, boolean shouldEncode) throws Exception JavaDoc
357     {
358         String JavaDoc encodedPassword = HTUU.encode(userName + ":" + password);
359         
360         String JavaDoc argString = "";
361         if(inHash != null)
362         {
363             if (shouldEncode)
364                 argString = "?" + toEncodedString(inHash, "UTF-8");
365             else
366                 argString = "?" + toString(inHash);
367         }
368         URL JavaDoc url = new URL JavaDoc(urlAddress + argString);
369         URLConnection JavaDoc connection = url.openConnection();
370         connection.setUseCaches(false);
371         connection.setRequestProperty("Authorization", "Basic " + encodedPassword);
372         InputStream JavaDoc inStream = null;
373         inStream = connection.getInputStream();
374         InputStreamReader JavaDoc inStreamReader = new InputStreamReader JavaDoc(inStream);
375         BufferedReader JavaDoc buffer = new BufferedReader JavaDoc(inStreamReader);
376         StringBuffer JavaDoc strbuf = new StringBuffer JavaDoc();
377         String JavaDoc line;
378         while((line = buffer.readLine()) != null)
379         {
380             strbuf.append(line);
381         }
382         String JavaDoc readData = strbuf.toString();
383         buffer.close();
384         return readData;
385     }
386     
387     
388     
389     public String JavaDoc getUrlContent(String JavaDoc urlAddress, String JavaDoc data, String JavaDoc userName, String JavaDoc password) throws Exception JavaDoc
390     {
391         String JavaDoc encodedPassword = HTUU.encode(userName + ":" + password);
392         
393         String JavaDoc argString = "?" + data;
394         
395         URL JavaDoc url = new URL JavaDoc(urlAddress + argString);
396         URLConnection JavaDoc connection = url.openConnection();
397         connection.setUseCaches(false);
398         connection.setRequestProperty("Authorization", "Basic " + encodedPassword);
399         InputStream JavaDoc inStream = null;
400         inStream = connection.getInputStream();
401         InputStreamReader JavaDoc inStreamReader = new InputStreamReader JavaDoc(inStream);
402         BufferedReader JavaDoc buffer = new BufferedReader JavaDoc(inStreamReader);
403         StringBuffer JavaDoc strbuf = new StringBuffer JavaDoc();
404         String JavaDoc line;
405         while((line = buffer.readLine()) != null)
406         {
407             strbuf.append(line);
408         }
409         String JavaDoc readData = strbuf.toString();
410         buffer.close();
411         return readData;
412     }
413     
414     
415     
416     /**
417      * This method gets information form an URL and returns an input stream.It
418      * throws an exception if anything goes wrong.
419      * It returns a input stream so that you can return objects.
420      * (Works like most 'doGet' methods)
421      *
422      * @param urlAddress The address of the URL you would like to get information from.
423      * @param inHash The parameters you would like to get from the URL.
424      * @return A input stream.
425      * @exception java.lang.Exception
426      */

427     
428     public InputStream JavaDoc getURLStream(String JavaDoc urlAddress, Hashtable JavaDoc inHash) throws Exception JavaDoc
429     {
430         String JavaDoc argString = "";
431         if(inHash != null)
432         {
433             argString = "?" + toEncodedString(inHash, "UTF-8");
434         }
435         URL JavaDoc url = new URL JavaDoc(urlAddress + argString);
436         URLConnection JavaDoc connection = url.openConnection();
437         connection.setUseCaches(false);
438         InputStream JavaDoc inStream = null;
439         inStream = connection.getInputStream();
440         return inStream;
441     }
442     
443     /**
444      * This method gets a cookie.
445      *
446      * @param cookieName
447      */

448
449     public String JavaDoc getCookie(HttpServletRequest JavaDoc request, String JavaDoc cookieName)
450     {
451         if(request != null)
452         {
453             Cookie JavaDoc[] cookies = request.getCookies();
454             if(cookies != null)
455             {
456                 for(int i=0; i<cookies.length; i++)
457                 {
458                     Cookie JavaDoc cookie = cookies[i];
459                     if(cookie.getName().equals(cookieName))
460                         return cookie.getValue();
461                 }
462             }
463         }
464         
465         return null;
466     }
467
468
469     /**
470      * This method converts the request-object to a hashtable instead.
471      */

472     
473     public Hashtable JavaDoc requestToHashtable(HttpServletRequest JavaDoc request)
474     {
475         Hashtable JavaDoc parameters = new Hashtable JavaDoc();
476         
477         if(request != null)
478         {
479             for (Enumeration JavaDoc e = request.getParameterNames(); e.hasMoreElements() ;)
480             {
481                 String JavaDoc name = (String JavaDoc)e.nextElement();
482                 String JavaDoc value = (String JavaDoc)request.getParameter(name);
483                 parameters.put(name, value);
484             }
485         }
486                 
487         return parameters;
488         
489     }
490
491     
492     /**
493      * Encodes a hash table to an URL encoded string.
494      *
495      * @param inHash The hash table you would like to encode
496      * @return A URL encoded string.
497      */

498         
499     private String JavaDoc toEncodedString(Hashtable JavaDoc inHash, String JavaDoc encoding) throws Exception JavaDoc
500     {
501         StringBuffer JavaDoc buffer = new StringBuffer JavaDoc();
502         Enumeration JavaDoc names = inHash.keys();
503         while(names.hasMoreElements())
504         {
505             String JavaDoc name = names.nextElement().toString();
506             String JavaDoc value = inHash.get(name).toString();
507             buffer.append(URLEncoder.encode(name, encoding) + "=" + URLEncoder.encode(value, encoding));
508             if(names.hasMoreElements())
509             {
510                 buffer.append("&");
511             }
512         }
513         return buffer.toString();
514     }
515     
516     private String JavaDoc toString(Hashtable JavaDoc inHash)
517     {
518         StringBuffer JavaDoc buffer = new StringBuffer JavaDoc();
519         Enumeration JavaDoc names = inHash.keys();
520         while(names.hasMoreElements())
521         {
522             String JavaDoc name = names.nextElement().toString();
523             String JavaDoc value = inHash.get(name).toString();
524             buffer.append(name + "=" + value);
525             if(names.hasMoreElements())
526             {
527                 buffer.append("&");
528             }
529         }
530         return buffer.toString();
531     }
532 }
533
Popular Tags