0
# Apache HttpComponents Fluent API
1
2
Apache HttpComponents Client fluent API provides a simplified and intuitive interface for making HTTP requests. It follows the fluent interface design pattern, enabling method chaining for building and executing HTTP requests with minimal boilerplate code.
3
4
## Package Information
5
6
- **Package Name**: fluent-hc
7
- **Package Type**: maven
8
- **Language**: Java
9
- **Group ID**: org.apache.httpcomponents
10
- **Artifact ID**: fluent-hc
11
- **Installation**: Add to Maven pom.xml:
12
13
```xml
14
<dependency>
15
<groupId>org.apache.httpcomponents</groupId>
16
<artifactId>fluent-hc</artifactId>
17
<version>4.5.14</version>
18
</dependency>
19
```
20
21
## Core Imports
22
23
```java
24
import org.apache.http.client.fluent.Request;
25
import org.apache.http.client.fluent.Response;
26
import org.apache.http.client.fluent.Content;
27
import org.apache.http.client.fluent.Executor;
28
import org.apache.http.client.fluent.Form;
29
import org.apache.http.client.fluent.Async;
30
```
31
32
## Basic Usage
33
34
```java
35
import org.apache.http.client.fluent.Request;
36
import org.apache.http.client.fluent.Form;
37
import org.apache.http.entity.ContentType;
38
import java.io.IOException;
39
40
// Simple GET request
41
String content = Request.Get("http://example.com/api/data")
42
.execute()
43
.returnContent()
44
.asString();
45
46
// POST request with JSON body
47
String response = Request.Post("http://example.com/api/users")
48
.addHeader("Content-Type", "application/json")
49
.bodyString("{\"name\":\"John\",\"email\":\"john@example.com\"}", ContentType.APPLICATION_JSON)
50
.execute()
51
.returnContent()
52
.asString();
53
54
// Form POST request
55
String result = Request.Post("http://example.com/login")
56
.bodyForm(Form.form()
57
.add("username", "user")
58
.add("password", "pass")
59
.build())
60
.execute()
61
.returnContent()
62
.asString();
63
```
64
65
## Architecture
66
67
The fluent API is built around several key components:
68
69
- **Request**: Main entry point for building HTTP requests with method chaining
70
- **Response**: Wrapper for handling HTTP responses with multiple consumption options
71
- **Content**: Reusable container for response content with multiple access methods
72
- **Executor**: Context manager for multiple requests with shared authentication and cookies
73
- **Form**: Builder for HTML form data (name-value pairs)
74
- **Async**: Asynchronous request execution with Future-based results
75
76
## Capabilities
77
78
### HTTP Request Operations
79
80
Create and configure HTTP requests using fluent method chaining with support for all standard HTTP methods.
81
82
```java { .api }
83
// Static factory methods for creating requests
84
public static Request Get(String uri);
85
public static Request Get(URI uri);
86
public static Request Post(String uri);
87
public static Request Post(URI uri);
88
public static Request Put(String uri);
89
public static Request Put(URI uri);
90
public static Request Delete(String uri);
91
public static Request Delete(URI uri);
92
public static Request Head(String uri);
93
public static Request Head(URI uri);
94
public static Request Options(String uri);
95
public static Request Options(URI uri);
96
public static Request Patch(String uri);
97
public static Request Patch(URI uri);
98
public static Request Trace(String uri);
99
public static Request Trace(URI uri);
100
```
101
102
[HTTP Request Operations](./request-operations.md)
103
104
### Response Handling
105
106
Process HTTP responses using multiple consumption patterns with automatic resource management.
107
108
```java { .api }
109
public class Response {
110
public Content returnContent() throws ClientProtocolException, IOException;
111
public HttpResponse returnResponse() throws IOException;
112
public void saveContent(File file) throws IOException;
113
public void discardContent();
114
public <T> T handleResponse(ResponseHandler<T> handler) throws ClientProtocolException, IOException;
115
}
116
```
117
118
[Response Handling](./response-handling.md)
119
120
### Authentication and Session Management
121
122
Manage authentication credentials, cookies, and connection pooling across multiple HTTP requests.
123
124
```java { .api }
125
public class Executor {
126
public static Executor newInstance();
127
public static Executor newInstance(HttpClient httpclient);
128
public Executor auth(String username, String password);
129
public Executor auth(HttpHost host, String username, String password);
130
public Response execute(Request request) throws ClientProtocolException, IOException;
131
}
132
```
133
134
[Authentication and Session Management](./executor-auth.md)
135
136
### Asynchronous Operations
137
138
Execute HTTP requests asynchronously using Future-based patterns with callback support.
139
140
```java { .api }
141
public class Async {
142
public static Async newInstance();
143
public <T> Future<T> execute(Request request, ResponseHandler<T> handler);
144
public <T> Future<T> execute(Request request, ResponseHandler<T> handler, FutureCallback<T> callback);
145
public Future<Content> execute(Request request);
146
public Future<Content> execute(Request request, FutureCallback<Content> callback);
147
}
148
```
149
150
[Asynchronous Operations](./async-operations.md)
151
152
## Core Types
153
154
```java { .api }
155
// Content container for response data
156
public class Content {
157
public static final Content NO_CONTENT;
158
public Content(byte[] raw, ContentType type);
159
public ContentType getType();
160
public byte[] asBytes();
161
public String asString();
162
public String asString(Charset charset);
163
public InputStream asStream();
164
}
165
166
// Form builder for HTML form data
167
public class Form {
168
public static Form form();
169
public Form add(String name, String value);
170
public List<NameValuePair> build();
171
}
172
173
// ContentResponseHandler for custom response processing
174
public class ContentResponseHandler extends AbstractResponseHandler<Content> {
175
public ContentResponseHandler();
176
public Content handleEntity(HttpEntity entity) throws IOException;
177
}
178
```
179
180
### Form Builder Usage
181
182
The Form class provides a convenient way to build form data for POST requests:
183
184
```java
185
import org.apache.http.client.fluent.Form;
186
187
// Create form with multiple fields
188
Form loginForm = Form.form()
189
.add("username", "john.doe")
190
.add("password", "secret123")
191
.add("remember_me", "true");
192
193
// Use with POST request
194
String response = Request.Post("https://example.com/login")
195
.bodyForm(loginForm.build())
196
.execute()
197
.returnContent()
198
.asString();
199
200
// Form parameters with special characters
201
Form dataForm = Form.form()
202
.add("query", "search term with spaces")
203
.add("category", "news & events")
204
.add("language", "en-US");
205
```
206
207
## Exception Handling
208
209
The fluent API throws standard Java exceptions:
210
211
- `IOException` - For I/O errors during request execution
212
- `ClientProtocolException` - For HTTP protocol violations and errors
213
- `UnsupportedOperationException` - For invalid operations (e.g., setting body on GET request)
214
- `IllegalStateException` - For response reuse attempts after consumption
215
216
## Thread Safety
217
218
- **Request objects**: Not thread-safe, create new instances per thread
219
- **Response objects**: Not thread-safe, consume only once
220
- **Content objects**: Thread-safe and reusable
221
- **Executor**: Thread-safe, can be shared across threads
222
- **Async**: Thread-safe for concurrent request execution