KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > objectweb > speedo > j2eedo > common > 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.j2eedo.common;
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     static TraceTime traceTime = new TraceTime();
49
50     /**
51      * Method getURL. This static method provides with the way to get and http response.
52      *
53      * @param urlString is the URL to be invoked
54      * @param paramString is the list of parameters like
55      * param1=value1&param2=value2&param3=....
56      * @param method POST or GET
57      * @return String flux HTTP de retour.
58      * @throws Exception when the getURL method fails due to unfound URL, or server errors
59      */

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

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

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

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

219     private static void setCookies(URLConnection JavaDoc con) {
220         Enumeration JavaDoc en = cookies.keys();
221         String JavaDoc cookieString;
222         String JavaDoc key = "";
223         String JavaDoc val = "";
224         for (cookieString = "";
225             en.hasMoreElements();
226             cookieString = cookieString + (key + "=" + val + ";")) {
227             key = (String JavaDoc) en.nextElement();
228             val = (String JavaDoc) cookies.get(key);
229         }
230         //System.out.println("Init cookies :" + cookieString);
231
con.setRequestProperty("Cookie", cookieString);
232     }
233 }
234
Popular Tags