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.Arrays;
36  import java.util.Date;
37  import java.util.Locale;
38  import java.util.TimeZone;
39  
40  import org.apache.http.Header;
41  import org.apache.http.HttpEntity;
42  import org.apache.http.HttpEntityEnclosingRequest;
43  import org.apache.http.HttpHost;
44  import org.apache.http.HttpVersion;
45  import org.apache.http.NameValuePair;
46  import org.apache.http.client.ClientProtocolException;
47  import org.apache.http.client.entity.UrlEncodedFormEntity;
48  import org.apache.http.client.methods.HttpDelete;
49  import org.apache.http.client.methods.HttpGet;
50  import org.apache.http.client.methods.HttpHead;
51  import org.apache.http.client.methods.HttpOptions;
52  import org.apache.http.client.methods.HttpPost;
53  import org.apache.http.client.methods.HttpPut;
54  import org.apache.http.client.methods.HttpRequestBase;
55  import org.apache.http.client.methods.HttpTrace;
56  import org.apache.http.client.params.HttpClientParamConfig;
57  import org.apache.http.conn.params.ConnRoutePNames;
58  import org.apache.http.entity.ByteArrayEntity;
59  import org.apache.http.entity.ContentType;
60  import org.apache.http.entity.FileEntity;
61  import org.apache.http.entity.InputStreamEntity;
62  import org.apache.http.entity.StringEntity;
63  import org.apache.http.params.CoreConnectionPNames;
64  import org.apache.http.params.CoreProtocolPNames;
65  import org.apache.http.params.HttpParams;
66  import org.apache.http.protocol.HTTP;
67  
68  @SuppressWarnings("deprecation")
69  public class Request {
70  
71      public static final String DATE_FORMAT = "EEE, dd MMM yyyy HH:mm:ss zzz";
72      public static final Locale DATE_LOCALE = Locale.US;
73      public static final TimeZone TIME_ZONE = TimeZone.getTimeZone("GMT");
74  
75      private final HttpRequestBase request;
76      private final HttpParams localParams;
77  
78      private SimpleDateFormat dateFormatter;
79  
80      public static Request Get(final URI uri) {
81          return new Request(new HttpGet(uri));
82      }
83  
84      public static Request Get(final String uri) {
85          return new Request(new HttpGet(uri));
86      }
87  
88      public static Request Head(final URI uri) {
89          return new Request(new HttpHead(uri));
90      }
91  
92      public static Request Head(final String uri) {
93          return new Request(new HttpHead(uri));
94      }
95  
96      public static Request Post(final URI uri) {
97          return new Request(new HttpPost(uri));
98      }
99  
100     public static Request Post(final String uri) {
101         return new Request(new HttpPost(uri));
102     }
103 
104     public static Request Put(final URI uri) {
105         return new Request(new HttpPut(uri));
106     }
107 
108     public static Request Put(final String uri) {
109         return new Request(new HttpPut(uri));
110     }
111 
112     public static Request Trace(final URI uri) {
113         return new Request(new HttpTrace(uri));
114     }
115 
116     public static Request Trace(final String uri) {
117         return new Request(new HttpTrace(uri));
118     }
119 
120     public static Request Delete(final URI uri) {
121         return new Request(new HttpDelete(uri));
122     }
123 
124     public static Request Delete(final String uri) {
125         return new Request(new HttpDelete(uri));
126     }
127 
128     public static Request Options(final URI uri) {
129         return new Request(new HttpOptions(uri));
130     }
131 
132     public static Request Options(final String uri) {
133         return new Request(new HttpOptions(uri));
134     }
135 
136     Request(final HttpRequestBase request) {
137         super();
138         this.request = request;
139         this.localParams = request.getParams();
140     }
141 
142     HttpRequestBase getHttpRequest() {
143         return this.request;
144     }
145 
146     public Response execute() throws ClientProtocolException, IOException {
147         this.request.setConfig(HttpClientParamConfig.getRequestConfig(this.localParams));
148         return new Response(Executor.CLIENT.execute(this.request));
149     }
150 
151     public void abort() throws UnsupportedOperationException {
152         this.request.abort();
153     }
154 
155     //// HTTP header operations
156 
157     public Request addHeader(final Header header) {
158         this.request.addHeader(header);
159         return this;
160     }
161 
162     public Request addHeader(final String name, final String value) {
163         this.request.addHeader(name, value);
164         return this;
165     }
166 
167     public Request removeHeader(final Header header) {
168         this.request.removeHeader(header);
169         return this;
170     }
171 
172     public Request removeHeaders(final String name) {
173         this.request.removeHeaders(name);
174         return this;
175     }
176 
177     public Request setHeaders(final Header[] headers) {
178         this.request.setHeaders(headers);
179         return this;
180     }
181 
182     public Request setCacheControl(final String cacheControl) {
183         this.request.setHeader(HttpHeader.CACHE_CONTROL, cacheControl);
184         return this;
185     }
186 
187     private SimpleDateFormat getDateFormat() {
188         if (this.dateFormatter == null) {
189             this.dateFormatter = new SimpleDateFormat(DATE_FORMAT, DATE_LOCALE);
190             this.dateFormatter.setTimeZone(TIME_ZONE);
191         }
192         return this.dateFormatter;
193     }
194 
195     public Request setDate(final Date date) {
196         this.request.setHeader(HttpHeader.DATE, getDateFormat().format(date));
197         return this;
198     }
199 
200     public Request setIfModifiedSince(final Date date) {
201         this.request.setHeader(HttpHeader.IF_MODIFIED_SINCE, getDateFormat().format(date));
202         return this;
203     }
204 
205     public Request setIfUnmodifiedSince(final Date date) {
206         this.request.setHeader(HttpHeader.IF_UNMODIFIED_SINCE, getDateFormat().format(date));
207         return this;
208     }
209 
210     /**
211      * @deprecated (4.3)
212      */
213     @Deprecated
214     public Request config(final String param, final Object object) {
215         this.localParams.setParameter(param, object);
216         return this;
217     }
218 
219     /**
220      * @deprecated (4.3)
221      */
222     @Deprecated
223     public Request removeConfig(final String param) {
224         this.localParams.removeParameter(param);
225         return this;
226     }
227 
228     //// HTTP protocol parameter operations
229 
230     public Request version(final HttpVersion version) {
231         this.request.setProtocolVersion(version);
232         return this;
233     }
234 
235     /**
236      * This parameter can no longer be used at the request level.
237      * @deprecated (4.3)
238      */
239     @Deprecated
240     public Request elementCharset(final String charset) {
241         return config(CoreProtocolPNames.HTTP_ELEMENT_CHARSET, charset);
242     }
243 
244     public Request useExpectContinue() {
245         return config(CoreProtocolPNames.USE_EXPECT_CONTINUE, true);
246     }
247 
248     public Request userAgent(final String agent) {
249         this.request.setHeader(HTTP.USER_AGENT, agent);
250         return this;
251     }
252 
253     //// HTTP connection parameter operations
254 
255     public Request socketTimeout(final int timeout) {
256         return config(CoreConnectionPNames.SO_TIMEOUT, timeout);
257     }
258 
259     public Request connectTimeout(final int timeout) {
260         return config(CoreConnectionPNames.CONNECTION_TIMEOUT, timeout);
261     }
262 
263     public Request staleConnectionCheck(final boolean b) {
264         return config(CoreConnectionPNames.STALE_CONNECTION_CHECK, b);
265     }
266 
267     //// HTTP connection route operations
268 
269     public Request viaProxy(final HttpHost proxy) {
270         return config(ConnRoutePNames.DEFAULT_PROXY, proxy);
271     }
272 
273     //// HTTP entity operations
274 
275     public Request body(final HttpEntity entity) {
276         if (this.request instanceof HttpEntityEnclosingRequest) {
277             ((HttpEntityEnclosingRequest) this.request).setEntity(entity);
278         } else {
279             throw new IllegalStateException(this.request.getMethod()
280                     + " request cannot enclose an entity");
281         }
282         return this;
283     }
284 
285     public Request bodyForm(final Iterable <? extends NameValuePair> formParams, final Charset charset) {
286         return body(new UrlEncodedFormEntity(formParams, charset));
287     }
288 
289     public Request bodyForm(final Iterable <? extends NameValuePair> formParams) {
290         return bodyForm(formParams, HTTP.DEF_CONTENT_CHARSET);
291     }
292 
293     public Request bodyForm(final NameValuePair... formParams) {
294         return bodyForm(Arrays.asList(formParams), HTTP.DEF_CONTENT_CHARSET);
295     }
296 
297     public Request bodyString(final String s, final ContentType contentType) {
298         return body(new StringEntity(s, contentType));
299     }
300 
301     public Request bodyFile(final File file, final ContentType contentType) {
302         return body(new FileEntity(file, contentType));
303     }
304 
305     public Request bodyByteArray(final byte[] b) {
306         return body(new ByteArrayEntity(b));
307     }
308 
309     public Request bodyByteArray(final byte[] b, final int off, final int len) {
310         return body(new ByteArrayEntity(b, off, len));
311     }
312 
313     public Request bodyStream(final InputStream instream) {
314         return body(new InputStreamEntity(instream, -1));
315     }
316 
317     public Request bodyStream(final InputStream instream, final ContentType contentType) {
318         return body(new InputStreamEntity(instream, -1, contentType));
319     }
320 
321     @Override
322     public String toString() {
323         return this.request.getRequestLine().toString();
324     }
325 
326 }