View Javadoc

1   /*
2    * Copyright 2007-2012 the original author or authors.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *      http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  
17  package org.springbyexample.httpclient;
18  
19  import java.io.ByteArrayInputStream;
20  import java.io.IOException;
21  import java.io.InputStream;
22  import java.util.Map;
23  
24  import org.apache.commons.httpclient.HttpException;
25  import org.apache.commons.httpclient.HttpMethod;
26  import org.apache.commons.httpclient.methods.ByteArrayRequestEntity;
27  import org.apache.commons.httpclient.methods.InputStreamRequestEntity;
28  import org.apache.commons.httpclient.methods.PostMethod;
29  import org.apache.commons.httpclient.methods.RequestEntity;
30  import org.slf4j.Logger;
31  import org.slf4j.LoggerFactory;
32  import org.springframework.stereotype.Component;
33  
34  /**
35   * Template for easier use of <code>HttpClient</code>.
36   * 
37   * @author David Winterfeldt
38   */
39  @Component
40  public class HttpClientTemplate extends AbstractHttpClientTemplate<RequestEntity> {
41  
42      final Logger logger = LoggerFactory.getLogger(HttpClientTemplate.class);
43  
44      /**
45       * Constructor.
46       */
47      public HttpClientTemplate() {}
48  
49      /**
50       * Constructor.
51       * 
52       * @param   defaultUri      Default uri.
53       */
54      public HttpClientTemplate(String defaultUri) {
55          super(defaultUri, false);
56      }
57  
58      /**
59       * Constructor.
60       * 
61       * @param   defaultUri      Default uri.
62       * @param   init            Whether or not to initialize the bean.
63       */
64      public HttpClientTemplate(String defaultUri, boolean init) {
65          super(defaultUri, init);
66      }
67  
68      /**
69       * Execute post method.
70       * 
71       * @param   input           Byte array <code>RequestEntity</code> to post 
72       *                          for the request's data.
73       */
74      public void executePostMethod(byte[] input) {
75          executePostMethod(input, null);
76      }
77      
78      /**
79       * Execute post method.
80       * 
81       * @param   input           Byte array <code>RequestEntity</code> to post 
82       *                          for the request's data.
83       * @param   callback        Callback with HTTP method's response.
84       */
85      public void executePostMethod(byte[] input, ResponseCallback<?> callback) {
86          executePostMethod(defaultUri,  
87                            (input != null ? new ByteArrayRequestEntity(input) : null), 
88                            null, callback);
89      }
90      
91      /**
92       * Execute post method.
93       * 
94       * @param   input           <code>String</code> to post 
95       *                          for the request's data.
96       */
97      public void executePostMethod(String input) {
98          executePostMethod(input, null);
99      }
100 
101     /**
102      * Execute post method.
103      * 
104      * @param   input           <code>String</code> to post 
105      *                          for the request's data.
106      * @param   callback        Callback with HTTP method's response.
107      */
108     public void executePostMethod(String input, ResponseCallback<?> callback) {
109         executePostMethod((input != null ? new ByteArrayInputStream(input.getBytes()) : null),
110                           callback);
111     }
112 
113     /**
114      * Execute post method.
115      * 
116      * @param   input           <code>InputStream</code> to post 
117      *                          for the request's data.
118      */
119     public void executePostMethod(InputStream input) {
120         executePostMethod(input, null);
121     }
122 
123     /**
124      * Execute post method.
125      * 
126      * @param   input           <code>InputStream</code> to post 
127      *                          for the request's data.
128      * @param   callback        Callback with HTTP method's response.
129      */
130     public void executePostMethod(InputStream input, ResponseCallback<?> callback) {
131         executePostMethod(defaultUri, new InputStreamRequestEntity(input), null, callback);
132     }
133     
134     /**
135      * Execute post method.
136      * 
137      * @param   uri             URI to use when processing this HTTP request instead 
138      *                          of using the default URI.
139      * @param   requestPayload  <code>RequestEntity</code> data to post.
140      * @param   hParams         Parameters for the HTTP post.
141      * @param   callback        Callback with HTTP method's response.
142      */
143     public void executePostMethod(String uri,  
144                                   RequestEntity requestPayload, Map<String, String> hParams,
145                                   ResponseCallback<?> callback) {
146         PostMethod post = new PostMethod(uri);
147         
148         if (requestPayload != null) {
149             post.setRequestEntity(requestPayload);
150         }
151         
152         processHttpMethodParams(post, hParams);
153         
154         processHttpMethod(post, callback);
155     }
156 
157     /**
158      * Processes <code>HttpMethod</code> by executing the method, 
159      * validating the response, and calling the callback.
160      * 
161      * @param   httpMethod      <code>HttpMethod</code> to process.
162      * @param   callback        Callback with HTTP method's response.
163      */
164     protected void processHttpMethod(HttpMethod httpMethod, ResponseCallback<?> callback) {
165         try {
166             client.executeMethod(httpMethod);
167             
168             validateResponse(httpMethod);
169             
170             if (callback instanceof ResponseByteCallback) {
171                 ((ResponseByteCallback)callback).doWithResponse(httpMethod.getResponseBody());
172             } else if (callback instanceof ResponseStreamCallback) {
173                 ((ResponseStreamCallback)callback).doWithResponse(httpMethod.getResponseBodyAsStream());
174             } else if (callback instanceof ResponseStringCallback) {
175                 ((ResponseStringCallback)callback).doWithResponse(httpMethod.getResponseBodyAsString());
176             }
177         } catch (HttpException e) {
178             throw new HttpAccessException(e.getMessage(), e, httpMethod.getStatusCode());
179         } catch (IOException e) {
180             throw new HttpAccessException(e.getMessage(), e);
181         } finally {
182             httpMethod.releaseConnection();
183         }
184     }
185     
186 }