View Javadoc

1   /*
2    * $Id: SimpleHTTPClient.java 22774 2011-08-27 17:31:44Z mariano.capurro $
3    * --------------------------------------------------------------------------------------
4    * Copyright (c) MuleSoft, Inc.  All rights reserved.  http://www.mulesoft.com
5    *
6    * The software in this package is published under the terms of the CPAL v1.0
7    * license, a copy of which has been included with this distribution in the
8    * LICENSE.txt file.
9    */
10  
11  package org.mule.example.launcher;
12  
13  import java.io.BufferedReader;
14  import java.io.InputStreamReader;
15  import java.io.OutputStreamWriter;
16  import java.net.URL;
17  import java.net.URLConnection;
18  import java.util.Map;
19  
20  /**
21   * <code>SimpleHTTPClient</code> is a simple class that handles GET and POST HTTP
22   * requests.
23   */
24  public class SimpleHTTPClient
25  {
26      private final static String URL_KEY = "url";
27      private final static String METHOD_KEY = "method";
28  
29      /**
30       *
31       */
32      public SimpleHTTPClient()
33      {
34      }
35  
36      /**
37       * Performs a HTTP GET or HTTP POST request and returns the contents.
38       * 
39       * @param data <code>Map</code> instance containing the URL (should start with
40       *            http://) and the method (GET or POST)
41       * @return The contents
42       */
43      public HTTPResponse httpClient(Object data)
44      {
45          if (data instanceof Map<?, ?>)
46          {
47              Map<?, ?> params = (Map<?, ?>) data;
48  
49              String url = String.valueOf(params.get(URL_KEY));
50              String method = params.containsKey(METHOD_KEY) ? String.valueOf(params.get(METHOD_KEY)) : "GET";
51  
52              if (method == null || method.equalsIgnoreCase("GET"))
53              {
54                  return buildResponse(doGet(url));
55              }
56              else if (method.equalsIgnoreCase("POST"))
57              {
58                  return buildResponse(doPost(url));
59              }
60              else
61              {
62                  // Invalid method!
63                  return buildResponse("Error: Invalid method " + method.toUpperCase());
64              }
65          }
66          else
67          {
68              // No input parameters
69              return buildResponse("Error: Missing URL & method input parameters");
70          }
71      }
72  
73      /**
74       * @param response
75       * @return
76       */
77      private HTTPResponse buildResponse(String response)
78      {
79          return new HTTPResponse(response);
80      }
81  
82      /**
83       * @param strUrl
84       * @return
85       */
86      private String doGet(String strUrl)
87      {
88          BufferedReader rd = null;
89          try
90          {
91              // Send data
92              URL url = new URL(strUrl);
93              URLConnection conn = url.openConnection();
94              conn.setDefaultUseCaches(false);
95  
96              // Get the response
97              rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
98              String line;
99              StringBuffer contents = new StringBuffer();
100             while ((line = rd.readLine()) != null)
101             {
102                 contents.append(line);
103                 contents.append('\n');
104             }
105 
106             return contents.toString().trim();
107         }
108         catch (Exception ex)
109         {
110             return "Error: " + ex.getMessage();
111         }
112         finally
113         {
114             close(rd);
115         }
116 
117     }
118 
119     /**
120      * @param strUrl
121      * @return
122      */
123     private String doPost(String strUrl)
124     {
125         OutputStreamWriter wr = null;
126         BufferedReader rd = null;
127         try
128         {
129             // Construct data
130             String data = "";
131 
132             // Send data
133             URL url = new URL(strUrl);
134             URLConnection conn = url.openConnection();
135             conn.setDoOutput(true);
136             conn.setDefaultUseCaches(false);
137 
138             wr = new OutputStreamWriter(conn.getOutputStream());
139             wr.write(data);
140             wr.flush();
141 
142             // Get the response
143             rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
144             String line;
145             StringBuffer contents = new StringBuffer();
146             while ((line = rd.readLine()) != null)
147             {
148                 contents.append(line);
149                 contents.append('\n');
150             }
151 
152             return contents.toString().trim();
153         }
154         catch (Exception ex)
155         {
156             return "Error: " + ex.getMessage();
157         }
158         finally
159         {
160             close(wr);
161             close(rd);
162         }
163     }
164 
165     /**
166      * Silently closes a <code>OutputStreamWriter</code>
167      * 
168      * @param wr
169      */
170     private void close(OutputStreamWriter wr)
171     {
172         try
173         {
174             wr.close();
175         }
176         catch (Exception e)
177         {
178             // Do nothing
179         }
180     }
181 
182     /**
183      * Silently closes a <code>BufferedReader</code>
184      * 
185      * @param rd
186      */
187     private void close(BufferedReader rd)
188     {
189         try
190         {
191             rd.close();
192         }
193         catch (Exception e)
194         {
195             // Do nothing
196         }
197     }
198 }