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