View Javadoc

1   /*
2    * ====================================================================
3    * Licensed to the Apache Software Foundation (ASF) under one
4    * or more contributor license agreements.  See the NOTICE file
5    * distributed with this work for additional information
6    * regarding copyright ownership.  The ASF licenses this file
7    * to you under the Apache License, Version 2.0 (the
8    * "License"); you may not use this file except in compliance
9    * with the License.  You may obtain a copy of the License at
10   *
11   *   http://www.apache.org/licenses/LICENSE-2.0
12   *
13   * Unless required by applicable law or agreed to in writing,
14   * software distributed under the License is distributed on an
15   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16   * KIND, either express or implied.  See the License for the
17   * specific language governing permissions and limitations
18   * under the License.
19   * ====================================================================
20   *
21   * This software consists of voluntary contributions made by many
22   * individuals on behalf of the Apache Software Foundation.  For more
23   * information on the Apache Software Foundation, please see
24   * <http://www.apache.org/>.
25   *
26   */
27  
28  package org.apache.http.protocol;
29  
30  import java.io.IOException;
31  
32  import org.apache.http.HttpClientConnection;
33  import org.apache.http.HttpEntityEnclosingRequest;
34  import org.apache.http.HttpException;
35  import org.apache.http.HttpRequest;
36  import org.apache.http.HttpResponse;
37  import org.apache.http.HttpStatus;
38  import org.apache.http.HttpVersion;
39  import org.apache.http.ProtocolException;
40  import org.apache.http.ProtocolVersion;
41  import org.apache.http.annotation.Immutable;
42  import org.apache.http.util.Args;
43  
44  /**
45   * <tt>HttpRequestExecutor</tt> is a client side HTTP protocol handler based
46   * on the blocking (classic) I/O model.
47   * <p/>
48   * <tt>HttpRequestExecutor</tt> relies on {@link HttpProcessor} to generate
49   * mandatory protocol headers for all outgoing messages and apply common,
50   * cross-cutting message transformations to all incoming and outgoing messages.
51   * Application specific processing can be implemented outside
52   * <tt>HttpRequestExecutor</tt> once the request has been executed and
53   * a response has been received.
54   *
55   * @since 4.0
56   */
57  @Immutable
58  public class HttpRequestExecutor {
59  
60      public static final int DEFAULT_WAIT_FOR_CONTINUE = 3000;
61  
62      private final int waitForContinue;
63  
64      /**
65       * Creates new instance of HttpRequestExecutor.
66       *
67       * @since 4.3
68       */
69      public HttpRequestExecutor(final int waitForContinue) {
70          super();
71          this.waitForContinue = Args.positive(waitForContinue, "Wait for continue time");
72      }
73  
74      public HttpRequestExecutor() {
75          this(DEFAULT_WAIT_FOR_CONTINUE);
76      }
77  
78      /**
79       * Decide whether a response comes with an entity.
80       * The implementation in this class is based on RFC 2616.
81       * <br/>
82       * Derived executors can override this method to handle
83       * methods and response codes not specified in RFC 2616.
84       *
85       * @param request   the request, to obtain the executed method
86       * @param response  the response, to obtain the status code
87       */
88      protected boolean canResponseHaveBody(final HttpRequest request,
89                                            final HttpResponse response) {
90  
91          if ("HEAD".equalsIgnoreCase(request.getRequestLine().getMethod())) {
92              return false;
93          }
94          final int status = response.getStatusLine().getStatusCode();
95          return status >= HttpStatus.SC_OK
96              && status != HttpStatus.SC_NO_CONTENT
97              && status != HttpStatus.SC_NOT_MODIFIED
98              && status != HttpStatus.SC_RESET_CONTENT;
99      }
100 
101     /**
102      * Sends the request and obtain a response.
103      *
104      * @param request   the request to execute.
105      * @param conn      the connection over which to execute the request.
106      *
107      * @return  the response to the request.
108      *
109      * @throws IOException in case of an I/O error.
110      * @throws HttpException in case of HTTP protocol violation or a processing
111      *   problem.
112      */
113     public HttpResponse execute(
114             final HttpRequest request,
115             final HttpClientConnection conn,
116             final HttpContext context) throws IOException, HttpException {
117         Args.notNull(request, "HTTP request");
118         Args.notNull(conn, "Client connection");
119         Args.notNull(context, "HTTP context");
120         try {
121             HttpResponse response = doSendRequest(request, conn, context);
122             if (response == null) {
123                 response = doReceiveResponse(request, conn, context);
124             }
125             return response;
126         } catch (final IOException ex) {
127             closeConnection(conn);
128             throw ex;
129         } catch (final HttpException ex) {
130             closeConnection(conn);
131             throw ex;
132         } catch (final RuntimeException ex) {
133             closeConnection(conn);
134             throw ex;
135         }
136     }
137 
138     private static void closeConnection(final HttpClientConnection conn) {
139         try {
140             conn.close();
141         } catch (final IOException ignore) {
142         }
143     }
144 
145     /**
146      * Pre-process the given request using the given protocol processor and
147      * initiates the process of request execution.
148      *
149      * @param request   the request to prepare
150      * @param processor the processor to use
151      * @param context   the context for sending the request
152      *
153      * @throws IOException in case of an I/O error.
154      * @throws HttpException in case of HTTP protocol violation or a processing
155      *   problem.
156      */
157     public void preProcess(
158             final HttpRequest request,
159             final HttpProcessor processor,
160             final HttpContext context) throws HttpException, IOException {
161         Args.notNull(request, "HTTP request");
162         Args.notNull(processor, "HTTP processor");
163         Args.notNull(context, "HTTP context");
164         context.setAttribute(HttpCoreContext.HTTP_REQUEST, request);
165         processor.process(request, context);
166     }
167 
168     /**
169      * Send the given request over the given connection.
170      * <p>
171      * This method also handles the expect-continue handshake if necessary.
172      * If it does not have to handle an expect-continue handshake, it will
173      * not use the connection for reading or anything else that depends on
174      * data coming in over the connection.
175      *
176      * @param request   the request to send, already
177      *                  {@link #preProcess preprocessed}
178      * @param conn      the connection over which to send the request,
179      *                  already established
180      * @param context   the context for sending the request
181      *
182      * @return  a terminal response received as part of an expect-continue
183      *          handshake, or
184      *          <code>null</code> if the expect-continue handshake is not used
185      *
186      * @throws IOException in case of an I/O error.
187      * @throws HttpException in case of HTTP protocol violation or a processing
188      *   problem.
189      */
190     protected HttpResponse doSendRequest(
191             final HttpRequest request,
192             final HttpClientConnection conn,
193             final HttpContext context) throws IOException, HttpException {
194         Args.notNull(request, "HTTP request");
195         Args.notNull(conn, "Client connection");
196         Args.notNull(context, "HTTP context");
197 
198         HttpResponse response = null;
199 
200         context.setAttribute(HttpCoreContext.HTTP_CONNECTION, conn);
201         context.setAttribute(HttpCoreContext.HTTP_REQ_SENT, Boolean.FALSE);
202 
203         conn.sendRequestHeader(request);
204         if (request instanceof HttpEntityEnclosingRequest) {
205             // Check for expect-continue handshake. We have to flush the
206             // headers and wait for an 100-continue response to handle it.
207             // If we get a different response, we must not send the entity.
208             boolean sendentity = true;
209             final ProtocolVersion ver =
210                 request.getRequestLine().getProtocolVersion();
211             if (((HttpEntityEnclosingRequest) request).expectContinue() &&
212                 !ver.lessEquals(HttpVersion.HTTP_1_0)) {
213 
214                 conn.flush();
215                 // As suggested by RFC 2616 section 8.2.3, we don't wait for a
216                 // 100-continue response forever. On timeout, send the entity.
217                 if (conn.isResponseAvailable(this.waitForContinue)) {
218                     response = conn.receiveResponseHeader();
219                     if (canResponseHaveBody(request, response)) {
220                         conn.receiveResponseEntity(response);
221                     }
222                     final int status = response.getStatusLine().getStatusCode();
223                     if (status < 200) {
224                         if (status != HttpStatus.SC_CONTINUE) {
225                             throw new ProtocolException(
226                                     "Unexpected response: " + response.getStatusLine());
227                         }
228                         // discard 100-continue
229                         response = null;
230                     } else {
231                         sendentity = false;
232                     }
233                 }
234             }
235             if (sendentity) {
236                 conn.sendRequestEntity((HttpEntityEnclosingRequest) request);
237             }
238         }
239         conn.flush();
240         context.setAttribute(HttpCoreContext.HTTP_REQ_SENT, Boolean.TRUE);
241         return response;
242     }
243 
244     /**
245      * Waits for and receives a response.
246      * This method will automatically ignore intermediate responses
247      * with status code 1xx.
248      *
249      * @param request   the request for which to obtain the response
250      * @param conn      the connection over which the request was sent
251      * @param context   the context for receiving the response
252      *
253      * @return  the terminal response, not yet post-processed
254      *
255      * @throws IOException in case of an I/O error.
256      * @throws HttpException in case of HTTP protocol violation or a processing
257      *   problem.
258      */
259     protected HttpResponse doReceiveResponse(
260             final HttpRequest request,
261             final HttpClientConnection conn,
262             final HttpContext context) throws HttpException, IOException {
263         Args.notNull(request, "HTTP request");
264         Args.notNull(conn, "Client connection");
265         Args.notNull(context, "HTTP context");
266         HttpResponse response = null;
267         int statusCode = 0;
268 
269         while (response == null || statusCode < HttpStatus.SC_OK) {
270 
271             response = conn.receiveResponseHeader();
272             if (canResponseHaveBody(request, response)) {
273                 conn.receiveResponseEntity(response);
274             }
275             statusCode = response.getStatusLine().getStatusCode();
276 
277         } // while intermediate response
278 
279         return response;
280     }
281 
282     /**
283      * Post-processes the given response using the given protocol processor and
284      * completes the process of request execution.
285      * <p>
286      * This method does <i>not</i> read the response entity, if any.
287      * The connection over which content of the response entity is being
288      * streamed from cannot be reused until
289      * {@link org.apache.http.util.EntityUtils#consume(org.apache.http.HttpEntity)}
290      * has been invoked.
291      *
292      * @param response  the response object to post-process
293      * @param processor the processor to use
294      * @param context   the context for post-processing the response
295      *
296      * @throws IOException in case of an I/O error.
297      * @throws HttpException in case of HTTP protocol violation or a processing
298      *   problem.
299      */
300     public void postProcess(
301             final HttpResponse response,
302             final HttpProcessor processor,
303             final HttpContext context) throws HttpException, IOException {
304         Args.notNull(response, "HTTP response");
305         Args.notNull(processor, "HTTP processor");
306         Args.notNull(context, "HTTP context");
307         context.setAttribute(HttpCoreContext.HTTP_RESPONSE, response);
308         processor.process(response, context);
309     }
310 
311 } // class HttpRequestExecutor