KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > objectweb > speedo > runtime > jmx > HTTPTools


1 /*
2  * Speedo: an implementation of JDO compliant personality on top of JORM generic
3  * I/O sub-system.
4  * Copyright (C) 2001-2004 France Telecom R&D
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this library; if not, write to the Free Software
18  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19  *
20  *
21  */

22 package org.objectweb.speedo.runtime.jmx;
23
24 import java.io.BufferedReader JavaDoc;
25 import java.io.InputStreamReader JavaDoc;
26 import java.io.OutputStream JavaDoc;
27 import java.net.HttpURLConnection JavaDoc;
28 import java.net.URL JavaDoc;
29 import java.net.URLConnection JavaDoc;
30 import java.util.Enumeration JavaDoc;
31 import java.util.Hashtable JavaDoc;
32 import java.util.StringTokenizer JavaDoc;
33
34 import org.objectweb.util.monolog.api.BasicLevel;
35 import org.objectweb.util.monolog.api.Logger;
36
37 /**
38  * This class provides with a simple method to perform some HTTP requests
39  * @author fmillevi@yahoo.com
40  */

41 public class HTTPTools {
42     static String JavaDoc redirectURL;
43
44     /**
45      * Liste des cookies
46      */

47     static Hashtable JavaDoc cookies = null;
48
49     /**
50      * Method getURL. This static method provides with the way to get and http response.
51      *
52      * @param urlString is the URL to be invoked
53      * @param paramString is the list of parameters like
54      * param1=value1&param2=value2&param3=....
55      * @param method POST or GET
56      * @return String flux HTTP de retour.
57      * @throws Exception when the getURL method fails due to unfound URL, or server errors
58      */

59     public static String JavaDoc getURL(
60         String JavaDoc urlString,
61         String JavaDoc paramString,
62         String JavaDoc method,
63         Logger logger)
64         throws Exception JavaDoc {
65         if (cookies == null) // C'est la premi�re connection.
66
{
67             // create the hashtable used to store cookies values
68
cookies = new Hashtable JavaDoc();
69             //getURL(urlString, paramString, method, logger);
70
}
71
72         String JavaDoc s = "Ok"; // return string
73

74         try {
75             if (!method.equalsIgnoreCase("post") && !paramString.equals("")) {
76                 urlString = urlString + "?" + paramString;
77             }
78
79             URL JavaDoc url = new URL JavaDoc(urlString);
80
81             HttpURLConnection JavaDoc conn = (HttpURLConnection JavaDoc) url.openConnection();
82
83             //String userPassword = "xxxx:yyyy";
84
//String encoding =
85
// new sun.misc.BASE64Encoder().encode(userPassword.getBytes());
86
//conn.setRequestProperty("Authorization", encoding);
87
//conn.setRequestProperty("Authorization", "Basic " + encoding);
88
conn.setRequestProperty("accept-language", "fr");
89             conn.setRequestProperty(
90                 "user-agent",
91                 "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0; .NET CLR 1.0.3705)");
92
93             conn.setRequestProperty ("connection", "Keep-Alive");
94             //conn.setRequestProperty ("accept-encoding", "gzip, deflate");
95

96             //accept http redirections
97
HttpURLConnection.setFollowRedirects(false);
98             //conn.setAllowUserInteraction(false);
99
conn.setUseCaches(false);
100
101             setCookies(conn);
102
103             if (method.equalsIgnoreCase("post")) {
104                 byte[] bytes = paramString.getBytes();
105                 conn.setDoOutput(true);
106                 conn.setDoInput(true);
107                 conn.setRequestMethod("POST");
108                 conn.setRequestProperty(
109                     "Content-length",
110                     String.valueOf(bytes.length));
111                 OutputStream JavaDoc out = conn.getOutputStream();
112                 out.write(bytes);
113                 out.flush();
114             }
115
116             s = "" + conn.getResponseCode();
117
118             if (conn.getResponseCode() != 200
119                 && conn.getResponseCode() != 302) {
120                 logger.log(BasicLevel.ERROR, "error " + conn.getResponseCode());
121             } else if (conn.getResponseCode() == 200) { //parse HTML response
122
//read HTML response
123
BufferedReader JavaDoc is =
124                     new BufferedReader JavaDoc(
125                         new InputStreamReader JavaDoc(conn.getInputStream()));
126                 String JavaDoc line = null;
127                 StringBuffer JavaDoc sourceTxt = new StringBuffer JavaDoc("");
128                 while ((line = is.readLine()) != null)
129                     sourceTxt.append(line);
130                 is.close();
131                 s = sourceTxt.toString();
132             }
133             getCookies(conn);
134             logger.log(
135                 BasicLevel.DEBUG,
136                 urlString + "\treturns:" + conn.getResponseCode() + " ");
137
138             while (s.equals("302")) {
139                 s = getURL(redirectURL, "", "", logger);
140             }
141
142             if (conn.getResponseCode() == 500)
143                 throw new Exception JavaDoc("the URL " + url + " fails.");
144
145             if (conn.getResponseCode() == 404)
146                 throw new Exception JavaDoc("the URL " + url + " not found.");
147
148         } catch (Exception JavaDoc ex) {
149             s = "";
150             logger.log(BasicLevel.DEBUG, urlString + " throws Execption!", ex);
151             throw ex;
152         }
153
154         return s;
155     }
156
157     /**
158      * Method getCookies. Gets and stores in the Hashtable the cookies values found in the HTTP response.
159      *
160      * @param con HTTP Connexion
161      */

162     private static void getCookies(HttpURLConnection JavaDoc con) {
163         int n = 1;
164
165         label0 : for (boolean done = false; !done; n++) {
166             String JavaDoc headerKey = con.getHeaderFieldKey(n);
167             String JavaDoc headerVal = con.getHeaderField(n);
168             if (headerKey != null || headerVal != null) {
169                 if ("location".equalsIgnoreCase(headerKey)) {
170                     redirectURL = headerVal;
171                 }
172                 if (!"Set-Cookie".equals(headerKey))
173                     continue;
174                 StringTokenizer JavaDoc st = new StringTokenizer JavaDoc(headerVal, ";");
175                 do {
176                     if (!st.hasMoreTokens())
177                         continue label0;
178                     String JavaDoc pair = st.nextToken();
179                     StringTokenizer JavaDoc stt = new StringTokenizer JavaDoc(pair, "=");
180                     while (stt.hasMoreTokens()) {
181                         String JavaDoc cookName = stt.nextToken();
182                         String JavaDoc cookValue = "";
183                         try {
184                             cookValue = stt.nextToken();
185                         } catch (Exception JavaDoc exception) {
186                         }
187                         if (!cookName.trim().equalsIgnoreCase("path")
188                             && !cookName.trim().equalsIgnoreCase("expires")) {
189                             //System.out.println("Set cookie :" + cookName +
190
// ":" + cookValue);
191
cookies.put(cookName.trim(), cookValue);
192                         }
193                     }
194                 }
195                 while (true);
196             }
197             done = true;
198         }
199     }
200
201     /**
202      * Method setCookies initialize the cookies values in the http request
203      * using the values found in the Hashtable
204      *
205      * @param con HTTP Connexion
206      */

207     private static void setCookies(URLConnection JavaDoc con) {
208         Enumeration JavaDoc en = cookies.keys();
209         String JavaDoc cookieString;
210         String JavaDoc key = "";
211         String JavaDoc val = "";
212         for (cookieString = "";
213             en.hasMoreElements();
214             cookieString = cookieString + (key + "=" + val + ";")) {
215             key = (String JavaDoc) en.nextElement();
216             val = (String JavaDoc) cookies.get(key);
217         }
218         //System.out.println("Init cookies :" + cookieString);
219
con.setRequestProperty("Cookie", cookieString);
220     }
221 }
222
Popular Tags