KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > ofbiz > base > util > HttpClient


1 /*
2  * $Id: HttpClient.java 6532 2006-01-20 06:44:07Z jonesde $
3  *
4  * Copyright (c) 2001-2005 The Open For Business Project - www.ofbiz.org
5  *
6  * Permission is hereby granted, free of charge, to any person obtaining a
7  * copy of this software and associated documentation files (the "Software"),
8  * to deal in the Software without restriction, including without limitation
9  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
10  * and/or sell copies of the Software, and to permit persons to whom the
11  * Software is furnished to do so, subject to the following conditions:
12  *
13  * The above copyright notice and this permission notice shall be included
14  * in all copies or substantial portions of the Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
17  * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
19  * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
20  * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT
21  * OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR
22  * THE USE OR OTHER DEALINGS IN THE SOFTWARE.
23  */

24 package org.ofbiz.base.util;
25
26 import java.io.BufferedReader JavaDoc;
27 import java.io.DataOutputStream JavaDoc;
28 import java.io.IOException JavaDoc;
29 import java.io.InputStream JavaDoc;
30 import java.io.InputStreamReader JavaDoc;
31 import java.net.HttpURLConnection JavaDoc;
32 import java.net.URL JavaDoc;
33 import java.net.URLConnection JavaDoc;
34 import java.util.HashMap JavaDoc;
35 import java.util.Iterator JavaDoc;
36 import java.util.Map JavaDoc;
37 import java.util.Set JavaDoc;
38
39 /**
40  * Send HTTP GET/POST requests.
41  *
42  * @author <a HREF="mailto:jaz@ofbiz.org">Andy Zeneski</a>
43  * @version $Rev: 6532 $
44  * @since 2.0
45  */

46 public class HttpClient {
47     
48     public static final String JavaDoc module = HttpClient.class.getName();
49     
50     private int timeout = 30000;
51     private boolean debug = false;
52     private boolean lineFeed = true;
53     private boolean followRedirects = true;
54     
55     private String JavaDoc url = null;
56     private String JavaDoc rawStream = null;
57     private String JavaDoc clientCertAlias = null;
58     private Map JavaDoc parameters = null;
59     private Map JavaDoc headers = null;
60     
61     private URL JavaDoc requestUrl = null;
62     private URLConnection JavaDoc con = null;
63
64     /** Creates an empty HttpClient object. */
65     public HttpClient() {}
66
67     /** Creates a new HttpClient object. */
68     public HttpClient(URL JavaDoc url) {
69         this.url = url.toExternalForm();
70     }
71
72     /** Creates a new HttpClient object. */
73     public HttpClient(String JavaDoc url) {
74         this.url = url;
75     }
76
77     /** Creates a new HttpClient object. */
78     public HttpClient(String JavaDoc url, Map JavaDoc parameters) {
79         this.url = url;
80         this.parameters = parameters;
81     }
82
83     /** Creates a new HttpClient object. */
84     public HttpClient(URL JavaDoc url, Map JavaDoc parameters) {
85         this.url = url.toExternalForm();
86         this.parameters = parameters;
87     }
88
89     /** Creates a new HttpClient object. */
90     public HttpClient(String JavaDoc url, Map JavaDoc parameters, Map JavaDoc headers) {
91         this.url = url;
92         this.parameters = parameters;
93         this.headers = headers;
94     }
95
96     /** Creates a new HttpClient object. */
97     public HttpClient(URL JavaDoc url, Map JavaDoc parameters, Map JavaDoc headers) {
98         this.url = url.toExternalForm();
99         this.parameters = parameters;
100         this.headers = headers;
101     }
102
103     /** When true overrides Debug.verboseOn() and forces debugging for this instance */
104     public void setDebug(boolean debug) {
105         this.debug = debug;
106     }
107
108     /** Sets the timeout for waiting for the connection (default 30sec) */
109     public void setTimeout(int timeout) {
110         this.timeout = timeout;
111     }
112     
113     /** Enables this request to follow redirect 3xx codes (default true) */
114      public void followRedirects(boolean followRedirects) {
115         this.followRedirects = followRedirects;
116     }
117     
118     /** Turns on or off line feeds in the request. (default is on) */
119     public void setLineFeed(boolean lineFeed) {
120         this.lineFeed = lineFeed;
121     }
122     
123     /** Set the raw stream for posts. */
124     public void setRawStream(String JavaDoc stream) {
125         this.rawStream = stream;
126     }
127     
128     /** Set the URL for this request. */
129     public void setUrl(URL JavaDoc url) {
130         this.url = url.toExternalForm();
131     }
132
133     /** Set the URL for this request. */
134     public void setUrl(String JavaDoc url) {
135         this.url = url;
136     }
137
138     /** Set the parameters for this request. */
139     public void setParameters(Map JavaDoc parameters) {
140         this.parameters = parameters;
141     }
142
143     /** Set an individual parameter for this request. */
144     public void setParameter(String JavaDoc name, String JavaDoc value) {
145         if (parameters == null)
146             parameters = new HashMap JavaDoc();
147         parameters.put(name, value);
148     }
149
150     /** Set the headers for this request. */
151     public void setHeaders(Map JavaDoc headers) {
152         this.headers = headers;
153     }
154
155     /** Set an individual header for this request. */
156     public void setHeader(String JavaDoc name, String JavaDoc value) {
157         if (headers == null)
158             headers = new HashMap JavaDoc();
159         headers.put(name, value);
160     }
161
162     /** Return a Map of headers. */
163     public Map JavaDoc getHeaders() {
164         return headers;
165     }
166
167     /** Return a Map of parameters. */
168     public Map JavaDoc getParameters() {
169         return parameters;
170     }
171
172     /** Return a string representing the requested URL. */
173     public String JavaDoc getUrl() {
174         return url;
175     }
176     
177     /** Sets the client certificate alias (from the keystore) to use for this SSL connection. */
178     public void setClientCertificateAlias(String JavaDoc alias) {
179         this.clientCertAlias = alias;
180     }
181     
182     /** Returns the alias of the client certificate to be used for this SSL connection. */
183     public String JavaDoc getClientCertificateAlias() {
184         return this.clientCertAlias;
185     }
186
187     /** Invoke HTTP request GET. */
188     public String JavaDoc get() throws HttpClientException {
189         return sendHttpRequest("get");
190     }
191
192     /** Invoke HTTP request GET. */
193     public InputStream JavaDoc getStream() throws HttpClientException {
194         return sendHttpRequestStream("get");
195     }
196
197     /** Invoke HTTP request POST. */
198     public String JavaDoc post() throws HttpClientException {
199         return sendHttpRequest("post");
200     }
201     
202     /** Invoke HTTP request POST and pass raw stream. */
203     public String JavaDoc post(String JavaDoc stream) throws HttpClientException {
204         this.rawStream = stream;
205         return sendHttpRequest("post");
206     }
207
208     /** Invoke HTTP request POST. */
209     public InputStream JavaDoc postStream() throws HttpClientException {
210         return sendHttpRequestStream("post");
211     }
212
213     /** Returns the value of the specified named response header field. */
214     public String JavaDoc getResponseHeader(String JavaDoc header) throws HttpClientException {
215         if (con == null) {
216             throw new HttpClientException("Connection not yet established");
217         }
218         return con.getHeaderField(header);
219     }
220
221     /** Returns the key for the nth response header field. */
222     public String JavaDoc getResponseHeaderFieldKey(int n) throws HttpClientException {
223         if (con == null) {
224             throw new HttpClientException("Connection not yet established");
225         }
226         return con.getHeaderFieldKey(n);
227     }
228
229     /** Returns the value for the nth response header field. It returns null of there are fewer then n fields. */
230     public String JavaDoc getResponseHeaderField(int n) throws HttpClientException {
231         if (con == null) {
232             throw new HttpClientException("Connection not yet established");
233         }
234         return con.getHeaderField(n);
235     }
236
237     /** Returns the content of the response. */
238     public Object JavaDoc getResponseContent() throws java.io.IOException JavaDoc, HttpClientException {
239         if (con == null) {
240             throw new HttpClientException("Connection not yet established");
241         }
242         return con.getContent();
243     }
244
245     /** Returns the content-type of the response. */
246     public String JavaDoc getResponseContentType() throws HttpClientException {
247         if (con == null) {
248             throw new HttpClientException("Connection not yet established");
249         }
250         return con.getContentType();
251     }
252
253     /** Returns the content length of the response */
254     public int getResponseContentLength() throws HttpClientException {
255         if (con == null) {
256             throw new HttpClientException("Connection not yet established");
257         }
258         return con.getContentLength();
259     }
260
261     /** Returns the content encoding of the response. */
262     public String JavaDoc getResponseContentEncoding() throws HttpClientException {
263         if (con == null) {
264             throw new HttpClientException("Connection not yet established");
265         }
266         return con.getContentEncoding();
267     }
268
269     private String JavaDoc sendHttpRequest(String JavaDoc method) throws HttpClientException {
270         InputStream JavaDoc in = sendHttpRequestStream(method);
271         if (in == null) return null;
272
273         StringBuffer JavaDoc buf = new StringBuffer JavaDoc();
274         try {
275             if (Debug.verboseOn() || debug) {
276                 try {
277                     Debug.log("ContentEncoding: " + con.getContentEncoding() + "; ContentType: " +
278                             con.getContentType() + " or: " + URLConnection.guessContentTypeFromStream(in), module);
279                 } catch (IOException JavaDoc ioe) {
280                     Debug.logWarning(ioe, "Caught exception printing content debugging information", module);
281                 }
282             }
283             
284             String JavaDoc charset = null;
285             String JavaDoc contentType = con.getContentType();
286             if (contentType == null) {
287                 try {
288                     contentType = URLConnection.guessContentTypeFromStream(in);
289                 } catch (IOException JavaDoc ioe) {
290                     Debug.logWarning(ioe, "Problems guessing content type from steam", module);
291                 }
292             }
293             
294             if (Debug.verboseOn() || debug) Debug.log("Content-Type: " + contentType, module);
295             
296             if (contentType != null) {
297                 contentType = contentType.toUpperCase();
298                 int charsetEqualsLoc = contentType.indexOf("=", contentType.indexOf("CHARSET"));
299                 int afterSemiColon = contentType.indexOf(";", charsetEqualsLoc);
300                 if (charsetEqualsLoc >= 0 && afterSemiColon >= 0) {
301                     charset = contentType.substring(charsetEqualsLoc + 1, afterSemiColon);
302                 } else if (charsetEqualsLoc >= 0) {
303                     charset = contentType.substring(charsetEqualsLoc + 1);
304                 }
305                 
306                 if (charset != null) charset = charset.trim();
307                 if (Debug.verboseOn() || debug) Debug.log("Getting text from HttpClient with charset: " + charset, module);
308             }
309             
310             BufferedReader JavaDoc post = new BufferedReader JavaDoc(charset == null ? new InputStreamReader JavaDoc(in) : new InputStreamReader JavaDoc(in, charset));
311             String JavaDoc line = new String JavaDoc();
312
313             if (Debug.verboseOn() || debug) Debug.log("---- HttpClient Response Content ----", module);
314             while ((line = post.readLine()) != null) {
315                 if (Debug.verboseOn() || debug) Debug.log("[HttpClient] : " + line, module);
316                 buf.append(line);
317                 if (lineFeed) {
318                     buf.append("\n");
319                 }
320             }
321         } catch (Exception JavaDoc e) {
322             throw new HttpClientException("Error processing input stream", e);
323         }
324         return buf.toString();
325     }
326
327     private InputStream JavaDoc sendHttpRequestStream(String JavaDoc method) throws HttpClientException {
328         // setup some SSL variables
329
SSLUtil.loadJsseProperties();
330             
331         String JavaDoc arguments = null;
332         InputStream JavaDoc in = null;
333
334         if (url == null) {
335             throw new HttpClientException("Cannot process a null URL.");
336         }
337
338         if (rawStream != null) {
339             arguments = rawStream;
340         } else if (parameters != null && parameters.size() > 0) {
341             arguments = UtilHttp.urlEncodeArgs(parameters, false);
342         }
343
344         // Append the arguments to the query string if GET.
345
if (method.equalsIgnoreCase("get") && arguments != null) {
346             url = url + "?" + arguments;
347         }
348
349         // Create the URL and open the connection.
350
try {
351             requestUrl = new URL JavaDoc(url);
352             con = URLConnector.openConnection(requestUrl, timeout, clientCertAlias);
353             if (Debug.verboseOn() || debug) Debug.log("Connection opened to : " + requestUrl.toExternalForm(), module);
354
355             if ((con instanceof HttpURLConnection JavaDoc)) {
356                 ((HttpURLConnection JavaDoc) con).setInstanceFollowRedirects(followRedirects);
357                 if (Debug.verboseOn() || debug) Debug.log("Connection is of type HttpURLConnection", module);
358             }
359
360             con.setDoOutput(true);
361             con.setUseCaches(false);
362             if (Debug.verboseOn() || debug) Debug.log("Do Input = true / Use Caches = false", module);
363
364             if (method.equalsIgnoreCase("post")) {
365                 con.setRequestProperty("Content-type", "application/x-www-form-urlencoded");
366                 con.setDoInput(true);
367                 if (Debug.verboseOn() || debug) Debug.log("Set content type to : application/x-www-form-urlencoded", module);
368             }
369
370             if (headers != null && headers.size() > 0) {
371                 Set JavaDoc headerSet = headers.keySet();
372                 Iterator JavaDoc i = headerSet.iterator();
373
374                 while (i.hasNext()) {
375                     String JavaDoc headerName = (String JavaDoc) i.next();
376                     String JavaDoc headerValue = (String JavaDoc) headers.get(headerName);
377                     con.setRequestProperty(headerName, headerValue);
378                     if (Debug.verboseOn() || debug) Debug.log("Header : " + headerName + " -> " + headerValue, module);
379                 }
380             } else {
381                 if (Debug.verboseOn() || debug) Debug.log("No headers to set", module);
382             }
383
384             if (method.equalsIgnoreCase("post")) {
385                 DataOutputStream JavaDoc out = new DataOutputStream JavaDoc(con.getOutputStream());
386                 if (Debug.verboseOn() || debug) Debug.log("Opened output stream", module);
387
388                 out.writeBytes(arguments);
389                 if (Debug.verboseOn() || debug) Debug.log("Wrote arguements (parameters) : " + arguments, module);
390
391                 out.flush();
392                 out.close();
393                 if (Debug.verboseOn() || debug) Debug.log("Flushed and closed buffer", module);
394             }
395
396             if (Debug.verboseOn() || debug) {
397                 Map JavaDoc headerFields = con.getHeaderFields();
398                 Debug.log("Header Fields : " + headerFields, module);
399             }
400
401             in = con.getInputStream();
402         } catch (IOException JavaDoc ioe) {
403             throw new HttpClientException("IO Error processing request", ioe);
404         } catch (Exception JavaDoc e) {
405             throw new HttpClientException("Error processing request", e);
406         }
407
408         return in;
409     }
410 }
411
Popular Tags