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