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