001: /*
002: * Speedo: an implementation of JDO compliant personality on top of JORM generic
003: * I/O sub-system.
004: * Copyright (C) 2001-2004 France Telecom R&D
005: *
006: * This library is free software; you can redistribute it and/or
007: * modify it under the terms of the GNU Lesser General Public
008: * License as published by the Free Software Foundation; either
009: * version 2 of the License, or (at your option) any later version.
010: *
011: * This library is distributed in the hope that it will be useful,
012: * but WITHOUT ANY WARRANTY; without even the implied warranty of
013: * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
014: * Lesser General Public License for more details.
015: *
016: * You should have received a copy of the GNU Lesser General Public
017: * License along with this library; if not, write to the Free Software
018: * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
019: *
020: *
021: */
022: package org.objectweb.speedo.j2eedo.common;
023:
024: import java.io.BufferedReader;
025: import java.io.InputStreamReader;
026: import java.io.OutputStream;
027: import java.net.HttpURLConnection;
028: import java.net.URL;
029: import java.net.URLConnection;
030: import java.util.Enumeration;
031: import java.util.Hashtable;
032: import java.util.StringTokenizer;
033:
034: import org.objectweb.util.monolog.api.BasicLevel;
035: import org.objectweb.util.monolog.api.Logger;
036:
037: /**
038: * This class provides with a simple method to perform some HTTP requests
039: * @author fmillevi@yahoo.com
040: */
041: public class HTTPTools {
042: static String redirectURL;
043:
044: /**
045: * Liste des cookies
046: */
047: static Hashtable cookies = null;
048: static TraceTime traceTime = new TraceTime();
049:
050: /**
051: * Method getURL. This static method provides with the way to get and http response.
052: *
053: * @param urlString is the URL to be invoked
054: * @param paramString is the list of parameters like
055: * param1=value1¶m2=value2¶m3=....
056: * @param method POST or GET
057: * @return String flux HTTP de retour.
058: * @throws Exception when the getURL method fails due to unfound URL, or server errors
059: */
060: public static String getURL(String urlString, String paramString,
061: String method, Logger logger) throws Exception {
062: if (cookies == null) // C'est la premiere connection.
063: {
064: // create the hashtable used to store cookies values
065: cookies = new Hashtable();
066: //getURL(urlString, paramString, method, logger);
067: }
068:
069: String s = "Ok"; // return string
070:
071: try {
072: if (!method.equalsIgnoreCase("post")
073: && !paramString.equals("")) {
074: urlString = urlString + "?" + paramString;
075: }
076:
077: URL url = new URL(urlString);
078:
079: traceTime.startTask("openConnection");
080: HttpURLConnection conn = (HttpURLConnection) url
081: .openConnection();
082: traceTime.endTask();
083:
084: //String userPassword = "xxxx:yyyy";
085: //String encoding =
086: // new sun.misc.BASE64Encoder().encode(userPassword.getBytes());
087: //conn.setRequestProperty("Authorization", encoding);
088: //conn.setRequestProperty("Authorization", "Basic " + encoding);
089: conn.setRequestProperty("accept-language", "fr");
090: conn
091: .setRequestProperty("user-agent",
092: "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0; .NET CLR 1.0.3705)");
093:
094: conn.setRequestProperty("connection", "Keep-Alive");
095: //conn.setRequestProperty ("accept-encoding", "gzip, deflate");
096:
097: //accept http redirections
098: HttpURLConnection.setFollowRedirects(false);
099: //conn.setAllowUserInteraction(false);
100: conn.setUseCaches(false);
101:
102: setCookies(conn);
103:
104: if (method.equalsIgnoreCase("post")) {
105: traceTime.startTask("set post parameters");
106: byte[] bytes = paramString.getBytes();
107: conn.setDoOutput(true);
108: conn.setDoInput(true);
109: conn.setRequestMethod("POST");
110: conn.setRequestProperty("Content-length", String
111: .valueOf(bytes.length));
112: OutputStream out = conn.getOutputStream();
113: out.write(bytes);
114: out.flush();
115: traceTime.endTask();
116: }
117:
118: traceTime.startTask("getResponseCode");
119: s = "" + conn.getResponseCode();
120: traceTime.endTask();
121:
122: if (conn.getResponseCode() != 200
123: && conn.getResponseCode() != 302) {
124: logger.log(BasicLevel.ERROR, "error "
125: + conn.getResponseCode());
126: } else if (conn.getResponseCode() == 200) { //parse HTML response
127: //read HTML response
128: BufferedReader is = new BufferedReader(
129: new InputStreamReader(conn.getInputStream()));
130: String line = null;
131: StringBuffer sourceTxt = new StringBuffer("");
132: while ((line = is.readLine()) != null)
133: sourceTxt.append(line);
134: is.close();
135: s = sourceTxt.toString();
136: }
137: getCookies(conn);
138: logger.log(BasicLevel.DEBUG, urlString + "\treturns:"
139: + conn.getResponseCode() + " ");
140: if (logger.isLoggable(BasicLevel.DEBUG)) {
141: logger.log(BasicLevel.DEBUG, traceTime.report());
142: }
143:
144: while (s.equals("302")) {
145: s = getURL(redirectURL, "", "", logger);
146: }
147:
148: if (conn.getResponseCode() == 500)
149: throw new Exception("the URL " + url + " fails.");
150:
151: if (conn.getResponseCode() == 404)
152: throw new Exception("the URL " + url + " not found.");
153:
154: } catch (Exception ex) {
155: s = "";
156: logger.log(BasicLevel.DEBUG, urlString
157: + " throws Execption!", ex);
158: throw ex;
159: } finally {
160: traceTime.reset();
161: }
162:
163: return s;
164: }
165:
166: /**
167: * Method getCookies. Gets and stores in the Hashtable the cookies values found in the HTTP response.
168: *
169: * @param con HTTP Connexion
170: */
171: private static void getCookies(HttpURLConnection con) {
172: int n = 1;
173:
174: label0: for (boolean done = false; !done; n++) {
175: String headerKey = con.getHeaderFieldKey(n);
176: String headerVal = con.getHeaderField(n);
177: if (headerKey != null || headerVal != null) {
178: if ("location".equalsIgnoreCase(headerKey)) {
179: redirectURL = headerVal;
180: }
181: if (!"Set-Cookie".equals(headerKey))
182: continue;
183: StringTokenizer st = new StringTokenizer(headerVal, ";");
184: do {
185: if (!st.hasMoreTokens())
186: continue label0;
187: String pair = st.nextToken();
188: StringTokenizer stt = new StringTokenizer(pair, "=");
189: while (stt.hasMoreTokens()) {
190: String cookName = stt.nextToken();
191: String cookValue = "";
192: try {
193: cookValue = stt.nextToken();
194: } catch (Exception exception) {
195: }
196: if (!cookName.trim().equalsIgnoreCase("path")
197: && !cookName.trim().equalsIgnoreCase(
198: "expires")) {
199: //System.out.println("Set cookie :" + cookName +
200: // ":" + cookValue);
201: cookies.put(cookName.trim(), cookValue);
202: }
203: }
204: } while (true);
205: }
206: done = true;
207: }
208: }
209:
210: /**
211: * Method setCookies initialize the cookies values in the http request
212: * using the values found in the Hashtable
213: *
214: * @param con HTTP Connexion
215: */
216: private static void setCookies(URLConnection con) {
217: Enumeration en = cookies.keys();
218: String cookieString;
219: String key = "";
220: String val = "";
221: for (cookieString = ""; en.hasMoreElements(); cookieString = cookieString
222: + (key + "=" + val + ";")) {
223: key = (String) en.nextElement();
224: val = (String) cookies.get(key);
225: }
226: //System.out.println("Init cookies :" + cookieString);
227: con.setRequestProperty("Cookie", cookieString);
228: }
229: }
|