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  package org.apache.http.client.fluent;
28  
29  import java.io.File;
30  import java.io.IOException;
31  import java.io.InputStream;
32  import java.net.URI;
33  import java.nio.charset.Charset;
34  import java.text.SimpleDateFormat;
35  import java.util.ArrayList;
36  import java.util.Arrays;
37  import java.util.Date;
38  import java.util.List;
39  import java.util.Locale;
40  import java.util.TimeZone;
41  
42  import org.apache.http.Consts;
43  import org.apache.http.Header;
44  import org.apache.http.HttpEntity;
45  import org.apache.http.HttpEntityEnclosingRequest;
46  import org.apache.http.HttpHost;
47  import org.apache.http.HttpVersion;
48  import org.apache.http.NameValuePair;
49  import org.apache.http.client.ClientProtocolException;
50  import org.apache.http.client.config.RequestConfig;
51  import org.apache.http.client.methods.HttpDelete;
52  import org.apache.http.client.methods.HttpGet;
53  import org.apache.http.client.methods.HttpHead;
54  import org.apache.http.client.methods.HttpOptions;
55  import org.apache.http.client.methods.HttpPost;
56  import org.apache.http.client.methods.HttpPut;
57  import org.apache.http.client.methods.HttpTrace;
58  import org.apache.http.client.utils.URLEncodedUtils;
59  import org.apache.http.entity.ContentType;
60  import org.apache.http.protocol.HTTP;
61  
62  public class Request {
63  
64      public static final String DATE_FORMAT = "EEE, dd MMM yyyy HH:mm:ss zzz";
65      public static final Locale DATE_LOCALE = Locale.US;
66      public static final TimeZone TIME_ZONE = TimeZone.getTimeZone("GMT");
67  
68      private final InternalHttpRequest request;
69      private final RequestConfig.Builder configBuilder;
70  
71      private SimpleDateFormat dateFormatter;
72  
73      public static Request Get(final URI uri) {
74          return new Request(new InternalHttpRequest(HttpGet.METHOD_NAME, uri));
75      }
76  
77      public static Request Get(final String uri) {
78          return new Request(new InternalHttpRequest(HttpGet.METHOD_NAME, URI.create(uri)));
79      }
80  
81      public static Request Head(final URI uri) {
82          return new Request(new InternalHttpRequest(HttpHead.METHOD_NAME, uri));
83      }
84  
85      public static Request Head(final String uri) {
86          return new Request(new InternalHttpRequest(HttpHead.METHOD_NAME, URI.create(uri)));
87      }
88  
89      public static Request Post(final URI uri) {
90          return new Request(new InternalEntityEnclosingHttpRequest(HttpPost.METHOD_NAME, uri));
91      }
92  
93      public static Request Post(final String uri) {
94          return new Request(new InternalEntityEnclosingHttpRequest(HttpPost.METHOD_NAME, URI.create(uri)));
95      }
96  
97      public static Request Put(final URI uri) {
98          return new Request(new InternalEntityEnclosingHttpRequest(HttpPut.METHOD_NAME, uri));
99      }
100 
101     public static Request Put(final String uri) {
102         return new Request(new InternalEntityEnclosingHttpRequest(HttpPut.METHOD_NAME, URI.create(uri)));
103     }
104 
105     public static Request Trace(final URI uri) {
106         return new Request(new InternalHttpRequest(HttpTrace.METHOD_NAME, uri));
107     }
108 
109     public static Request Trace(final String uri) {
110         return new Request(new InternalHttpRequest(HttpTrace.METHOD_NAME, URI.create(uri)));
111     }
112 
113     public static Request Delete(final URI uri) {
114         return new Request(new InternalHttpRequest(HttpDelete.METHOD_NAME, uri));
115     }
116 
117     public static Request Delete(final String uri) {
118         return new Request(new InternalHttpRequest(HttpDelete.METHOD_NAME, URI.create(uri)));
119     }
120 
121     public static Request Options(final URI uri) {
122         return new Request(new InternalHttpRequest(HttpOptions.METHOD_NAME, uri));
123     }
124 
125     public static Request Options(final String uri) {
126         return new Request(new InternalHttpRequest(HttpOptions.METHOD_NAME, URI.create(uri)));
127     }
128 
129     Request(final InternalHttpRequest request) {
130         super();
131         this.request = request;
132         this.configBuilder = RequestConfig.custom();
133     }
134 
135     InternalHttpRequest prepareRequest() {
136         this.request.setConfig(this.configBuilder.build());
137         return this.request;
138     }
139 
140     public Response execute() throws ClientProtocolException, IOException {
141         this.request.setConfig(this.configBuilder.build());
142         return new Response(Executor.CLIENT.execute(this.request));
143     }
144 
145     public void abort() throws UnsupportedOperationException {
146         this.request.abort();
147     }
148 
149     //// HTTP header operations
150 
151     public Request addHeader(final Header header) {
152         this.request.addHeader(header);
153         return this;
154     }
155 
156     /**
157      * @since 4.3
158      */
159     public Request setHeader(final Header header) {
160         this.request.setHeader(header);
161         return this;
162     }
163 
164     public Request addHeader(final String name, final String value) {
165         this.request.addHeader(name, value);
166         return this;
167     }
168 
169     /**
170      * @since 4.3
171      */
172     public Request setHeader(final String name, final String value) {
173         this.request.setHeader(name, value);
174         return this;
175     }
176 
177     public Request removeHeader(final Header header) {
178         this.request.removeHeader(header);
179         return this;
180     }
181 
182     public Request removeHeaders(final String name) {
183         this.request.removeHeaders(name);
184         return this;
185     }
186 
187     public Request setHeaders(final Header... headers) {
188         this.request.setHeaders(headers);
189         return this;
190     }
191 
192     public Request setCacheControl(final String cacheControl) {
193         this.request.setHeader(HttpHeader.CACHE_CONTROL, cacheControl);
194         return this;
195     }
196 
197     private SimpleDateFormat getDateFormat() {
198         if (this.dateFormatter == null) {
199             this.dateFormatter = new SimpleDateFormat(DATE_FORMAT, DATE_LOCALE);
200             this.dateFormatter.setTimeZone(TIME_ZONE);
201         }
202         return this.dateFormatter;
203     }
204 
205     public Request setDate(final Date date) {
206         this.request.setHeader(HttpHeader.DATE, getDateFormat().format(date));
207         return this;
208     }
209 
210     public Request setIfModifiedSince(final Date date) {
211         this.request.setHeader(HttpHeader.IF_MODIFIED_SINCE, getDateFormat().format(date));
212         return this;
213     }
214 
215     public Request setIfUnmodifiedSince(final Date date) {
216         this.request.setHeader(HttpHeader.IF_UNMODIFIED_SINCE, getDateFormat().format(date));
217         return this;
218     }
219 
220     /**
221      * This method has no effect. Do not use.
222      *
223      * @deprecated (4.3)
224      */
225     @Deprecated
226     public Request config(final String param, final Object object) {
227         return this;
228     }
229 
230     /**
231      * This method has no effect. Do not use.
232      *
233      * @deprecated (4.3)
234      */
235     @Deprecated
236     public Request removeConfig(final String param) {
237         return this;
238     }
239 
240     //// HTTP protocol parameter operations
241 
242     public Request version(final HttpVersion version) {
243         this.request.setProtocolVersion(version);
244         return this;
245     }
246 
247     /**
248      * This parameter can no longer be used at the request level.
249      * <p/>
250      * This method has no effect. Do not use.
251      * @deprecated (4.3)
252      */
253     @Deprecated
254     public Request elementCharset(final String charset) {
255         return this;
256     }
257 
258     public Request useExpectContinue() {
259         this.configBuilder.setExpectContinueEnabled(true);
260         return this;
261     }
262 
263     public Request userAgent(final String agent) {
264         this.request.setHeader(HTTP.USER_AGENT, agent);
265         return this;
266     }
267 
268     //// HTTP connection parameter operations
269 
270     public Request socketTimeout(final int timeout) {
271         this.configBuilder.setSocketTimeout(timeout);
272         return this;
273     }
274 
275     public Request connectTimeout(final int timeout) {
276         this.configBuilder.setConnectTimeout(timeout);
277         return this;
278     }
279 
280     /**
281      * @deprecated (4.4) Use {@link
282      *   org.apache.http.impl.conn.PoolingHttpClientConnectionManager#setValidateAfterInactivity(int)}
283      */
284     @Deprecated
285     public Request staleConnectionCheck(final boolean b) {
286         this.configBuilder.setStaleConnectionCheckEnabled(b);
287         return this;
288     }
289 
290     //// HTTP connection route operations
291 
292     public Request viaProxy(final HttpHost proxy) {
293         this.configBuilder.setProxy(proxy);
294         return this;
295     }
296 
297     /**
298      * @since 4.4
299      */
300     public Request viaProxy(final String proxy) {
301         this.configBuilder.setProxy(HttpHost.create(proxy));
302         return this;
303     }
304 
305     //// HTTP entity operations
306 
307     public Request body(final HttpEntity entity) {
308         if (this.request instanceof HttpEntityEnclosingRequest) {
309             ((HttpEntityEnclosingRequest) this.request).setEntity(entity);
310         } else {
311             throw new IllegalStateException(this.request.getMethod()
312                     + " request cannot enclose an entity");
313         }
314         return this;
315     }
316 
317     public Request bodyForm(final Iterable <? extends NameValuePair> formParams, final Charset charset) {
318         final List<NameValuePair> paramList = new ArrayList<NameValuePair>();
319         for (NameValuePair param : formParams) {
320             paramList.add(param);
321         }
322         final ContentType contentType = ContentType.create(URLEncodedUtils.CONTENT_TYPE, charset);
323         final String s = URLEncodedUtils.format(paramList, charset != null ? charset.name() : null);
324         return bodyString(s, contentType);
325     }
326 
327     public Request bodyForm(final Iterable <? extends NameValuePair> formParams) {
328         return bodyForm(formParams, Consts.ISO_8859_1);
329     }
330 
331     public Request bodyForm(final NameValuePair... formParams) {
332         return bodyForm(Arrays.asList(formParams), Consts.ISO_8859_1);
333     }
334 
335     public Request bodyString(final String s, final ContentType contentType) {
336         final Charset charset = contentType != null ? contentType.getCharset() : null;
337         final byte[] raw = charset != null ? s.getBytes(charset) : s.getBytes();
338         return body(new InternalByteArrayEntity(raw, contentType));
339     }
340 
341     public Request bodyFile(final File file, final ContentType contentType) {
342         return body(new InternalFileEntity(file, contentType));
343     }
344 
345     public Request bodyByteArray(final byte[] b) {
346         return body(new InternalByteArrayEntity(b));
347     }
348 
349     /**
350      * @since 4.4
351      */
352     public Request bodyByteArray(final byte[] b, final ContentType contentType) {
353         return body(new InternalByteArrayEntity(b, contentType));
354     }
355 
356     public Request bodyByteArray(final byte[] b, final int off, final int len) {
357         return body(new InternalByteArrayEntity(b, off, len));
358     }
359 
360     /**
361      * @since 4.4
362      */
363     public Request bodyByteArray(final byte[] b, final int off, final int len, final ContentType contentType) {
364         return body(new InternalByteArrayEntity(b, off, len, contentType));
365     }
366 
367     public Request bodyStream(final InputStream instream) {
368         return body(new InternalInputStreamEntity(instream, -1, null));
369     }
370 
371     public Request bodyStream(final InputStream instream, final ContentType contentType) {
372         return body(new InternalInputStreamEntity(instream, -1, contentType));
373     }
374 
375     @Override
376     public String toString() {
377         return this.request.getRequestLine().toString();
378     }
379 
380 }