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