0
# HTTP Operations
1
2
The core HTTP operations capability provides the fundamental HTTP client functionality for making GET, POST, PUT, DELETE and other HTTP requests with comprehensive request/response lifecycle management.
3
4
## HttpClient Class
5
6
The main entry point for all HTTP operations.
7
8
```java { .api }
9
public class HttpClient extends ContainerLifeCycle {
10
// Constructors
11
public HttpClient();
12
public HttpClient(HttpClientTransport transport);
13
public HttpClient(SslContextFactory.Client sslContextFactory);
14
15
// Lifecycle management
16
public void start() throws Exception;
17
public void stop() throws Exception;
18
public boolean isStarted();
19
public boolean isStopped();
20
21
// Simple GET operations (synchronous)
22
public ContentResponse GET(String uri) throws InterruptedException, ExecutionException, TimeoutException;
23
public ContentResponse GET(URI uri) throws InterruptedException, ExecutionException, TimeoutException;
24
25
// Request factory methods for POST
26
public Request POST(String uri);
27
public Request POST(URI uri);
28
29
// General request factory methods
30
public Request newRequest(String uri);
31
public Request newRequest(URI uri);
32
public Request newRequest(String host, int port);
33
34
// Configuration accessors
35
public RequestListeners getRequestListeners();
36
public HttpCookieStore getHttpCookieStore();
37
public void setHttpCookieStore(HttpCookieStore cookieStore);
38
public AuthenticationStore getAuthenticationStore();
39
public ProxyConfiguration getProxyConfiguration();
40
}
41
```
42
43
## Basic GET Operations
44
45
Simple synchronous GET requests that return a ContentResponse immediately.
46
47
### GET with String URI
48
49
```java
50
HttpClient client = new HttpClient();
51
client.start();
52
53
try {
54
ContentResponse response = client.GET("https://api.example.com/users");
55
System.out.println("Status: " + response.getStatus());
56
System.out.println("Content: " + response.getContentAsString());
57
} finally {
58
client.stop();
59
}
60
```
61
62
### GET with URI Object
63
64
```java
65
URI uri = URI.create("https://api.example.com/data");
66
ContentResponse response = client.GET(uri);
67
```
68
69
## Creating Custom Requests
70
71
For more complex requests, use the request factory methods that return a configurable Request object.
72
73
### POST Request Factory
74
75
```java
76
Request postRequest = client.POST("https://api.example.com/users");
77
// Further configure the request...
78
ContentResponse response = postRequest.send();
79
```
80
81
### General Request Factory
82
83
```java
84
Request request = client.newRequest("https://api.example.com/data")
85
.method(HttpMethod.PUT)
86
.header("Authorization", "Bearer token123")
87
.content(new StringRequestContent("application/json", jsonData));
88
89
ContentResponse response = request.send();
90
```
91
92
## Request Sending Patterns
93
94
### Synchronous Sending
95
96
Blocks until the response is complete:
97
98
```java
99
ContentResponse response = request.send();
100
```
101
102
### Asynchronous with Callback
103
104
Non-blocking with callback notification:
105
106
```java
107
request.send(result -> {
108
if (result.isSucceeded()) {
109
Response response = result.getResponse();
110
System.out.println("Success: " + response.getStatus());
111
} else {
112
System.err.println("Failed: " + result.getFailure());
113
}
114
});
115
```
116
117
### CompletableFuture Pattern
118
119
Returns a CompletableFuture for async composition:
120
121
```java
122
CompletableFuture<ContentResponse> future = request.send();
123
future.thenAccept(response -> {
124
System.out.println("Received: " + response.getStatus());
125
});
126
```
127
128
## Client Lifecycle
129
130
### Starting and Stopping
131
132
The HttpClient must be started before use and should be stopped when no longer needed:
133
134
```java
135
HttpClient client = new HttpClient();
136
137
// Start the client (required before any requests)
138
client.start();
139
140
try {
141
// Make requests...
142
ContentResponse response = client.GET("https://example.com");
143
} finally {
144
// Always stop the client to release resources
145
client.stop();
146
}
147
```
148
149
### Configuration Before Starting
150
151
All configuration must be done before starting the client:
152
153
```java
154
HttpClient client = new HttpClient();
155
156
// Configure before starting
157
client.setConnectTimeout(5000);
158
client.setIdleTimeout(30000);
159
client.setFollowRedirects(true);
160
161
client.start(); // Start after configuration
162
```
163
164
## Error Handling
165
166
### Synchronous Error Handling
167
168
```java
169
try {
170
ContentResponse response = client.GET("https://api.example.com/data");
171
if (response.getStatus() == 200) {
172
// Process successful response
173
String content = response.getContentAsString();
174
} else {
175
// Handle HTTP error status
176
System.err.println("HTTP Error: " + response.getStatus() + " " + response.getReason());
177
}
178
} catch (InterruptedException e) {
179
// Request was interrupted
180
Thread.currentThread().interrupt();
181
} catch (ExecutionException e) {
182
// Request execution failed
183
Throwable cause = e.getCause();
184
if (cause instanceof HttpRequestException) {
185
// Request-related error
186
} else if (cause instanceof HttpResponseException) {
187
// Response-related error
188
}
189
} catch (TimeoutException e) {
190
// Request timed out
191
}
192
```
193
194
### Asynchronous Error Handling
195
196
```java
197
request.send(result -> {
198
if (result.isSucceeded()) {
199
Response response = result.getResponse();
200
// Handle successful response
201
} else {
202
Throwable failure = result.getFailure();
203
if (failure instanceof HttpRequestException) {
204
// Request failed
205
} else if (failure instanceof HttpResponseException) {
206
// Response failed
207
} else {
208
// Other failure
209
}
210
}
211
});
212
```
213
214
## Usage Examples
215
216
### Simple REST API Client
217
218
```java
219
public class ApiClient {
220
private final HttpClient httpClient;
221
private final String baseUrl;
222
223
public ApiClient(String baseUrl) throws Exception {
224
this.httpClient = new HttpClient();
225
this.httpClient.start();
226
this.baseUrl = baseUrl;
227
}
228
229
public User getUser(long id) throws Exception {
230
ContentResponse response = httpClient.GET(baseUrl + "/users/" + id);
231
if (response.getStatus() == 200) {
232
return parseJson(response.getContentAsString(), User.class);
233
} else {
234
throw new ApiException("Failed to get user: " + response.getStatus());
235
}
236
}
237
238
public User createUser(User user) throws Exception {
239
String json = toJson(user);
240
ContentResponse response = httpClient.POST(baseUrl + "/users")
241
.header("Content-Type", "application/json")
242
.content(new StringRequestContent(json))
243
.send();
244
245
if (response.getStatus() == 201) {
246
return parseJson(response.getContentAsString(), User.class);
247
} else {
248
throw new ApiException("Failed to create user: " + response.getStatus());
249
}
250
}
251
252
public void close() throws Exception {
253
httpClient.stop();
254
}
255
}
256
```
257
258
### Batch Request Processing
259
260
```java
261
List<CompletableFuture<ContentResponse>> futures = new ArrayList<>();
262
263
for (String url : urls) {
264
CompletableFuture<ContentResponse> future = client.newRequest(url).send();
265
futures.add(future);
266
}
267
268
// Wait for all requests to complete
269
CompletableFuture<Void> allFutures = CompletableFuture.allOf(
270
futures.toArray(new CompletableFuture[0])
271
);
272
273
allFutures.thenRun(() -> {
274
for (CompletableFuture<ContentResponse> future : futures) {
275
try {
276
ContentResponse response = future.get();
277
System.out.println("Response: " + response.getStatus());
278
} catch (Exception e) {
279
System.err.println("Request failed: " + e.getMessage());
280
}
281
}
282
});
283
```