KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > lateralnz > common > util > HttpUtils


1 /* ====================================================================
2  * The LateralNZ Software License, Version 1.0
3  *
4  * Copyright (c) 2003 LateralNZ. All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  *
10  * 1. Redistributions of source code must retain the above copyright
11  * notice, this list of conditions and the following disclaimer.
12  *
13  * 2. Redistributions in binary form must reproduce the above copyright
14  * notice, this list of conditions and the following disclaimer in
15  * the documentation and/or other materials provided with the
16  * distribution.
17  *
18  * 3. The end-user documentation included with the redistribution,
19  * if any, must include the following acknowledgment:
20  * "This product includes software developed by
21  * LateralNZ (http://www.lateralnz.org/) and other third parties."
22  * Alternately, this acknowledgment may appear in the software itself,
23  * if and wherever such third-party acknowledgments normally appear.
24  *
25  * 4. The names "LateralNZ" must not be used to endorse or promote
26  * products derived from this software without prior written
27  * permission. For written permission, please
28  * contact oss@lateralnz.org.
29  *
30  * 5. Products derived from this software may not be called "Panther",
31  * or "Lateral" or "LateralNZ", nor may "PANTHER" or "LATERAL" or
32  * "LATERALNZ" appear in their name, without prior written
33  * permission of LateralNZ.
34  *
35  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
36  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
37  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
38  * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
39  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
40  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
41  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
42  * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
43  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
44  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
45  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
46  * SUCH DAMAGE.
47  * ====================================================================
48  *
49  * This software consists of voluntary contributions made by many
50  * individuals on behalf of LateralNZ. For more
51  * information on Lateral, please see http://www.lateralnz.com/ or
52  * http://www.lateralnz.org
53  *
54  */

55 package org.lateralnz.common.util;
56
57 import java.io.BufferedReader JavaDoc;
58 import java.io.InputStream JavaDoc;
59 import java.io.InputStreamReader JavaDoc;
60 import java.io.OutputStream JavaDoc;
61 import java.net.URL JavaDoc;
62 import java.net.HttpURLConnection JavaDoc;
63
64 import org.apache.log4j.Logger;
65
66 import org.lateralnz.common.util.Constants;
67
68 /**
69  * standard HTTP functions
70  *
71  * @author J R Briggs
72  */

73 public class HttpUtils implements Constants {
74   
75   private static final Logger log = Logger.getLogger(HttpUtils.class.getName());
76   
77   public static final int GET_METHOD = 0;
78   public static final int POST_METHOD = 1;
79   public static final String JavaDoc POST = "POST";
80   public static final String JavaDoc GET = "GET";
81   private static final String JavaDoc CLOSE = "Close";
82   private static final String JavaDoc CONNECTION = "Connection";
83   private static final String JavaDoc CONTENT_TYPE = "Content-Type";
84   private static final String JavaDoc CONTENT_LEN = "Content-Length"; // john, 27/08/2003.
85

86   private static final String JavaDoc SENT_TEXT1 = "Sent :: ";
87   private static final String JavaDoc SENT_TEXT2 = " (";
88   private static final String JavaDoc SENT_TEXT3 = ")";
89   
90   private HttpUtils() {
91   }
92   
93   public static final String JavaDoc send(String JavaDoc url, int method, String JavaDoc contentType, String JavaDoc body) throws Exception JavaDoc {
94     return send(url, method, null, contentType, body);
95   }
96   
97  /**
98   * send a 'request' to a remote server
99   * @param url the url to call. e.g. http://localhost:9090/controller
100   * @param method one of HttpUtils.GET_METHOD or HttpUtils.POST_METHOD
101   * @param contentType the content type of the request (e.g. text/xml)
102   * @param body in the case of a POST, this will contain the body of the post
103   */

104   public static final String JavaDoc send(String JavaDoc url, int method, String JavaDoc[][] extraHeaders, String JavaDoc contentType, String JavaDoc body) throws Exception JavaDoc {
105
106     // replace spaces with '+' for the url. -- jwang
107
if (!StringUtils.isEmpty(url)) {
108       url = StringUtils.replace(url, SPACE, PLUS);
109     }
110     
111     String JavaDoc sentMethod;
112     URL JavaDoc messageURL = new URL JavaDoc(url);
113     HttpURLConnection JavaDoc con = null;
114     OutputStream JavaDoc out = null;
115     InputStream JavaDoc in = null;
116     BufferedReader JavaDoc r = null;
117
118     try {
119       con = (HttpURLConnection JavaDoc)messageURL.openConnection();
120       
121       con.setRequestProperty(CONNECTION, CLOSE);
122       con.setDoInput(true);
123
124       if (extraHeaders != null) {
125         for (int i = 0; i < extraHeaders.length; i++) {
126           con.setRequestProperty(extraHeaders[i][0], extraHeaders[i][1]);
127         }
128       }
129       
130       if (method == GET_METHOD) {
131         con.setRequestMethod(GET);
132         con.setDoOutput(false);
133         sentMethod = GET;
134       }
135       else {
136         con.setRequestMethod(POST);
137         con.setDoOutput(true);
138         con.setRequestProperty(CONTENT_TYPE, contentType);
139
140         // jwang, 27/08/2003.
141
if(!StringUtils.isEmpty(body)) {
142           int length = body.length();
143           con.setRequestProperty(CONTENT_LEN, EMPTY+length);
144         }
145         else {
146           con.setRequestProperty(CONTENT_LEN, ZERO);
147         }
148
149         out = con.getOutputStream();
150         out.write(body.getBytes());
151         sentMethod = POST;
152       }
153
154       in = con.getInputStream();
155       r = new BufferedReader JavaDoc(new InputStreamReader JavaDoc(in));
156       String JavaDoc line;
157
158       StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
159       char[] buf = new char[1024];
160       int len;
161       while ((len = r.read(buf)) != -1) {
162         sb.append(buf, 0, len);
163       }
164
165       // assuming log4j has been correctly setup, this will go to another file
166
// from the main server log
167
//log.debug(SENT_TEXT1 + url + SENT_TEXT2 + sentMethod + SENT_TEXT3 + NEWLINE + body + NEWLINE + NEWLINE);
168
log.info("Sent: " + url);
169       log.info("Method: " + sentMethod);
170       //log.info("Body: " + body + NEWLINE + NEWLINE);
171

172       return sb.toString();
173     }
174     finally {
175       IOUtils.close(r);
176       IOUtils.close(in);
177       IOUtils.close(out);
178       IOUtils.disconnect(con);
179     }
180   }
181   
182   private static final int getMethod(String JavaDoc method) throws Exception JavaDoc {
183     if (method != null) {
184       if (method.equals(GET)) {
185         return GET_METHOD;
186       }
187       else if (method.equals(POST)) {
188         return POST_METHOD;
189       }
190     }
191     throw new Exception JavaDoc("invalid method : " + method);
192   }
193
194   // invokable from the command line
195
public static final void main(String JavaDoc[] args) throws Exception JavaDoc {
196     String JavaDoc url = args[0];
197     int method = getMethod(args[1]);
198     String JavaDoc contentType = args[2];
199     String JavaDoc body = StringUtils.readFromFile(args[3]);
200     
201     if (StringUtils.isEmpty(body)) {
202       throw new Exception JavaDoc("invalid file " + args[3]);
203     }
204     
205     System.out.println(HttpUtils.send(url, method, contentType, body));
206   }
207 }
Popular Tags