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  
28  package org.apache.http.client.methods;
29  
30  import java.net.URI;
31  import java.net.URISyntaxException;
32  import java.util.ArrayList;
33  import java.util.LinkedList;
34  import java.util.List;
35  
36  import org.apache.http.Header;
37  import org.apache.http.HeaderIterator;
38  import org.apache.http.HttpEntity;
39  import org.apache.http.HttpEntityEnclosingRequest;
40  import org.apache.http.HttpRequest;
41  import org.apache.http.NameValuePair;
42  import org.apache.http.ProtocolVersion;
43  import org.apache.http.annotation.NotThreadSafe;
44  import org.apache.http.client.config.RequestConfig;
45  import org.apache.http.client.entity.UrlEncodedFormEntity;
46  import org.apache.http.client.utils.URIBuilder;
47  import org.apache.http.message.BasicHeader;
48  import org.apache.http.message.BasicNameValuePair;
49  import org.apache.http.message.HeaderGroup;
50  import org.apache.http.protocol.HTTP;
51  import org.apache.http.util.Args;
52  
53  /**
54   * Builder for {@link HttpUriRequest} instances.
55   * <p/>
56   * Please note that this class treats parameters differently depending on composition
57   * of the request: if the request has a content entity explicitly set with
58   * {@link #setEntity(org.apache.http.HttpEntity)} or it is not an entity enclosing method
59   * (such as POST or PUT), parameters will be added to the query component of the request URI.
60   * Otherwise, parameters will be added as a URL encoded {@link UrlEncodedFormEntity entity}.
61   *
62   * @since 4.3
63   */
64  @NotThreadSafe
65  public class RequestBuilder {
66  
67      private String method;
68      private ProtocolVersion version;
69      private URI uri;
70      private HeaderGroup headergroup;
71      private HttpEntity entity;
72      private LinkedList<NameValuePair> parameters;
73      private RequestConfig config;
74  
75      RequestBuilder(final String method) {
76          super();
77          this.method = method;
78      }
79  
80      RequestBuilder() {
81          this(null);
82      }
83  
84      public static RequestBuilder create(final String method) {
85          Args.notBlank(method, "HTTP method");
86          return new RequestBuilder(method);
87      }
88  
89      public static RequestBuilder get() {
90          return new RequestBuilder(HttpGet.METHOD_NAME);
91      }
92  
93      public static RequestBuilder head() {
94          return new RequestBuilder(HttpHead.METHOD_NAME);
95      }
96  
97      public static RequestBuilder post() {
98          return new RequestBuilder(HttpPost.METHOD_NAME);
99      }
100 
101     public static RequestBuilder put() {
102         return new RequestBuilder(HttpPut.METHOD_NAME);
103     }
104 
105     public static RequestBuilder delete() {
106         return new RequestBuilder(HttpDelete.METHOD_NAME);
107     }
108 
109     public static RequestBuilder trace() {
110         return new RequestBuilder(HttpTrace.METHOD_NAME);
111     }
112 
113     public static RequestBuilder options() {
114         return new RequestBuilder(HttpOptions.METHOD_NAME);
115     }
116 
117     public static RequestBuilder copy(final HttpRequest request) {
118         Args.notNull(request, "HTTP request");
119         return new RequestBuilder().doCopy(request);
120     }
121 
122     private RequestBuilder doCopy(final HttpRequest request) {
123         if (request == null) {
124             return this;
125         }
126         method = request.getRequestLine().getMethod();
127         version = request.getRequestLine().getProtocolVersion();
128         if (request instanceof HttpUriRequest) {
129             uri = ((HttpUriRequest) request).getURI();
130         } else {
131             uri = URI.create(request.getRequestLine().getMethod());
132         }
133         if (headergroup == null) {
134             headergroup = new HeaderGroup();
135         }
136         headergroup.clear();
137         headergroup.setHeaders(request.getAllHeaders());
138         if (request instanceof HttpEntityEnclosingRequest) {
139             entity = ((HttpEntityEnclosingRequest) request).getEntity();
140         } else {
141             entity = null;
142         }
143         if (request instanceof Configurable) {
144             this.config = ((Configurable) request).getConfig();
145         } else {
146             this.config = null;
147         }
148         this.parameters = null;
149         return this;
150     }
151 
152     public String getMethod() {
153         return method;
154     }
155 
156     public ProtocolVersion getVersion() {
157         return version;
158     }
159 
160     public RequestBuilder setVersion(final ProtocolVersion version) {
161         this.version = version;
162         return this;
163     }
164 
165     public URI getUri() {
166         return uri;
167     }
168 
169     public RequestBuilder setUri(final URI uri) {
170         this.uri = uri;
171         return this;
172     }
173 
174     public RequestBuilder setUri(final String uri) {
175         this.uri = uri != null ? URI.create(uri) : null;
176         return this;
177     }
178 
179     public Header getFirstHeader(final String name) {
180         return headergroup != null ? headergroup.getFirstHeader(name) : null;
181     }
182 
183     public Header getLastHeader(final String name) {
184         return headergroup != null ? headergroup.getLastHeader(name) : null;
185     }
186 
187     public Header[] getHeaders(final String name) {
188         return headergroup != null ? headergroup.getHeaders(name) : null;
189     }
190 
191     public RequestBuilder addHeader(final Header header) {
192         if (headergroup == null) {
193             headergroup = new HeaderGroup();
194         }
195         headergroup.addHeader(header);
196         return this;
197     }
198 
199     public RequestBuilder addHeader(final String name, final String value) {
200         if (headergroup == null) {
201             headergroup = new HeaderGroup();
202         }
203         this.headergroup.addHeader(new BasicHeader(name, value));
204         return this;
205     }
206 
207     public RequestBuilder removeHeader(final Header header) {
208         if (headergroup == null) {
209             headergroup = new HeaderGroup();
210         }
211         headergroup.removeHeader(header);
212         return this;
213     }
214 
215     public RequestBuilder removeHeaders(final String name) {
216         if (name == null || headergroup == null) {
217             return this;
218         }
219         for (final HeaderIterator i = headergroup.iterator(); i.hasNext(); ) {
220             final Header header = i.nextHeader();
221             if (name.equalsIgnoreCase(header.getName())) {
222                 i.remove();
223             }
224         }
225         return this;
226     }
227 
228     public RequestBuilder setHeader(final Header header) {
229         if (headergroup == null) {
230             headergroup = new HeaderGroup();
231         }
232         this.headergroup.updateHeader(header);
233         return this;
234     }
235 
236     public RequestBuilder setHeader(final String name, final String value) {
237         if (headergroup == null) {
238             headergroup = new HeaderGroup();
239         }
240         this.headergroup.updateHeader(new BasicHeader(name, value));
241         return this;
242     }
243 
244     public HttpEntity getEntity() {
245         return entity;
246     }
247 
248     public RequestBuilder setEntity(final HttpEntity entity) {
249         this.entity = entity;
250         return this;
251     }
252 
253     public List<NameValuePair> getParameters() {
254         return parameters != null ? new ArrayList<NameValuePair>(parameters) :
255             new ArrayList<NameValuePair>();
256     }
257 
258     public RequestBuilder addParameter(final NameValuePair nvp) {
259         Args.notNull(nvp, "Name value pair");
260         if (parameters == null) {
261             parameters = new LinkedList<NameValuePair>();
262         }
263         parameters.add(nvp);
264         return this;
265     }
266 
267     public RequestBuilder addParameter(final String name, final String value) {
268         return addParameter(new BasicNameValuePair(name, value));
269     }
270 
271     public RequestBuilder addParameters(final NameValuePair... nvps) {
272         for (final NameValuePair nvp: nvps) {
273             addParameter(nvp);
274         }
275         return this;
276     }
277 
278     public RequestConfig getConfig() {
279         return config;
280     }
281 
282     public RequestBuilder setConfig(final RequestConfig config) {
283         this.config = config;
284         return this;
285     }
286 
287     public HttpUriRequest build() {
288         final HttpRequestBase result;
289         URI uri = this.uri != null ? this.uri : URI.create("/");
290         HttpEntity entity = this.entity;
291         if (parameters != null && !parameters.isEmpty()) {
292             if (entity == null && (HttpPost.METHOD_NAME.equalsIgnoreCase(method)
293                     || HttpPut.METHOD_NAME.equalsIgnoreCase(method))) {
294                 entity = new UrlEncodedFormEntity(parameters, HTTP.DEF_CONTENT_CHARSET);
295             } else {
296                 try {
297                     uri = new URIBuilder(uri).addParameters(parameters).build();
298                 } catch (final URISyntaxException ex) {
299                     // should never happen
300                 }
301             }
302         }
303         if (entity == null) {
304             result = new InternalRequest(method);
305         } else {
306             final InternalEntityEclosingRequest request = new InternalEntityEclosingRequest(method);
307             request.setEntity(entity);
308             result = request;
309         }
310         result.setProtocolVersion(this.version);
311         result.setURI(uri);
312         if (this.headergroup != null) {
313             result.setHeaders(this.headergroup.getAllHeaders());
314         }
315         result.setConfig(this.config);
316         return result;
317     }
318 
319     static class InternalRequest extends HttpRequestBase {
320 
321         private final String method;
322 
323         InternalRequest(final String method) {
324             super();
325             this.method = method;
326         }
327 
328         @Override
329         public String getMethod() {
330             return this.method;
331         }
332 
333     }
334 
335     static class InternalEntityEclosingRequest extends HttpEntityEnclosingRequestBase {
336 
337         private final String method;
338 
339         InternalEntityEclosingRequest(final String method) {
340             super();
341             this.method = method;
342         }
343 
344         @Override
345         public String getMethod() {
346             return this.method;
347         }
348 
349     }
350 
351 }