0
# HTTP Client Operations
1
2
Comprehensive HTTP client functionality providing low-level HTTP operations, pipeline construction with middleware support, and REST proxy capabilities for method-based service clients.
3
4
## Capabilities
5
6
### HttpClient Interface
7
8
Core HTTP client for sending HTTP requests with reactive and blocking patterns.
9
10
```java { .api }
11
/**
12
* An interface to be implemented by any azure-core plugin that wishes to provide an alternate HTTP implementation.
13
*/
14
interface HttpClient {
15
/**
16
* Send the provided request asynchronously.
17
* @param request The HTTP request to send
18
* @return A Mono that emits the HTTP response
19
*/
20
Mono<HttpResponse> send(HttpRequest request);
21
22
/**
23
* Send the provided request asynchronously with context.
24
* @param request The HTTP request to send
25
* @param context Additional context that is passed through the Http pipeline during the service call
26
* @return A Mono that emits the HTTP response
27
*/
28
default Mono<HttpResponse> send(HttpRequest request, Context context);
29
30
/**
31
* Sends the provided request synchronously with contextual information.
32
* @param request The HTTP request to send
33
* @param context Contextual information about the request
34
* @return The response
35
*/
36
default HttpResponse sendSync(HttpRequest request, Context context);
37
38
/**
39
* Create the default HttpClient implementation.
40
* @return Default HttpClient instance
41
*/
42
static HttpClient createDefault();
43
44
/**
45
* Create the default HttpClient implementation with options.
46
* @param clientOptions The HttpClient options to configure the client
47
* @return Default HttpClient instance
48
*/
49
static HttpClient createDefault(HttpClientOptions clientOptions);
50
}
51
52
/**
53
* Service provider interface for HttpClient implementations.
54
*/
55
interface HttpClientProvider {
56
/**
57
* Creates a new HttpClient instance with default configuration.
58
* @return HttpClient instance
59
*/
60
HttpClient createInstance();
61
62
/**
63
* Creates a new HttpClient instance with the provided configuration.
64
* @param clientOptions Configuration for the HttpClient
65
* @return HttpClient instance
66
*/
67
HttpClient createInstance(HttpClientOptions clientOptions);
68
}
69
```
70
71
### HttpPipeline
72
73
Pipeline for processing HTTP requests through a series of policies for cross-cutting concerns like authentication, retry, and logging.
74
75
```java { .api }
76
/**
77
* The HTTP pipeline that HTTP requests and responses will flow through.
78
*/
79
class HttpPipeline {
80
/**
81
* Wraps this HttpPipeline in a RestProxy.
82
* @param restProxyClass Interface defining REST API methods
83
* @return RestProxy instance
84
*/
85
public <T> T create(Class<T> restProxyClass);
86
87
/**
88
* Sends the HTTP request through the pipeline.
89
* @param httpRequest HTTP request to send
90
* @return Mono emitting HTTP response
91
*/
92
public Mono<HttpResponse> send(HttpRequest httpRequest);
93
94
/**
95
* Sends the HTTP request through the pipeline with context.
96
* @param httpRequest HTTP request to send
97
* @param context Additional context for the request
98
* @return Mono emitting HTTP response
99
*/
100
public Mono<HttpResponse> send(HttpRequest httpRequest, Context context);
101
102
/**
103
* Gets the count of policies in this pipeline.
104
* @return Number of policies
105
*/
106
public int getPolicyCount();
107
108
/**
109
* Gets the policy at the specified index.
110
* @param index Policy index
111
* @return HttpPipelinePolicy at index
112
*/
113
public HttpPipelinePolicy getPolicy(int index);
114
}
115
116
/**
117
* Builder for creating HttpPipeline instances.
118
*/
119
class HttpPipelineBuilder {
120
/**
121
* Creates a new instance of HttpPipelineBuilder.
122
*/
123
public HttpPipelineBuilder();
124
125
/**
126
* Sets the HttpClient for the pipeline.
127
* @param httpClient HTTP client implementation
128
* @return HttpPipelineBuilder for method chaining
129
*/
130
public HttpPipelineBuilder httpClient(HttpClient httpClient);
131
132
/**
133
* Adds policies to the pipeline.
134
* @param policies Pipeline policies to add
135
* @return HttpPipelineBuilder for method chaining
136
*/
137
public HttpPipelineBuilder policies(HttpPipelinePolicy... policies);
138
139
/**
140
* Sets the ClientOptions that will configure the pipeline.
141
* @param clientOptions The ClientOptions instance
142
* @return HttpPipelineBuilder for method chaining
143
*/
144
public HttpPipelineBuilder clientOptions(ClientOptions clientOptions);
145
146
/**
147
* Sets the Tracer to trace logical and HTTP calls.
148
* @param tracer The Tracer instance
149
* @return HttpPipelineBuilder for method chaining
150
*/
151
public HttpPipelineBuilder tracer(Tracer tracer);
152
153
/**
154
* Builds the HttpPipeline.
155
* @return Configured HttpPipeline instance
156
*/
157
public HttpPipeline build();
158
}
159
```
160
161
### HttpRequest
162
163
HTTP request representation with method, URL, headers, and body support.
164
165
```java { .api }
166
/**
167
* The outgoing Http request.
168
*/
169
class HttpRequest {
170
/**
171
* Create a new HttpRequest instance.
172
* @param httpMethod HTTP method
173
* @param url Request URL
174
*/
175
public HttpRequest(HttpMethod httpMethod, String url);
176
177
/**
178
* Create a new HttpRequest instance.
179
* @param httpMethod HTTP method
180
* @param url Request URL
181
*/
182
public HttpRequest(HttpMethod httpMethod, URL url);
183
184
/**
185
* Gets the HTTP method for this request.
186
* @return HTTP method
187
*/
188
public HttpMethod getHttpMethod();
189
190
/**
191
* Gets the target address.
192
* @return Target URL
193
*/
194
public URL getUrl();
195
196
/**
197
* Sets the request URL.
198
* @param url Request URL
199
* @return Updated HttpRequest
200
*/
201
public HttpRequest setUrl(String url);
202
203
/**
204
* Sets the request URL.
205
* @param url Request URL
206
* @return Updated HttpRequest
207
*/
208
public HttpRequest setUrl(URL url);
209
210
/**
211
* Gets the request headers.
212
* @return HttpHeaders containing request headers
213
*/
214
public HttpHeaders getHeaders();
215
216
/**
217
* Sets a request header.
218
* @param name Header name
219
* @param value Header value
220
* @return Updated HttpRequest
221
*/
222
public HttpRequest setHeader(String name, String value);
223
224
/**
225
* Sets a request header.
226
* @param header HttpHeader to set
227
* @return Updated HttpRequest
228
*/
229
public HttpRequest setHeader(HttpHeader header);
230
231
/**
232
* Sets request headers, replacing any existing headers.
233
* @param headers Headers to set
234
* @return Updated HttpRequest
235
*/
236
public HttpRequest setHeaders(HttpHeaders headers);
237
238
/**
239
* Gets the request body.
240
* @return Request body as BinaryData
241
*/
242
public BinaryData getBody();
243
244
/**
245
* Sets the request body.
246
* @param body Request body
247
* @return Updated HttpRequest
248
*/
249
public HttpRequest setBody(String body);
250
251
/**
252
* Sets the request body.
253
* @param body Request body
254
* @return Updated HttpRequest
255
*/
256
public HttpRequest setBody(byte[] body);
257
258
/**
259
* Sets the request body.
260
* @param body Request body
261
* @return Updated HttpRequest
262
*/
263
public HttpRequest setBody(BinaryData body);
264
265
/**
266
* Gets the request body as Flux of ByteBuffer.
267
* @return Request body as Flux
268
*/
269
public Flux<ByteBuffer> getBodyAsByteBuffer();
270
271
/**
272
* Creates a copy of this HttpRequest.
273
* @return Copy of this request
274
*/
275
public HttpRequest copy();
276
}
277
```
278
279
### HttpResponse
280
281
HTTP response representation with status code, headers, and body access methods.
282
283
```java { .api }
284
/**
285
* The incoming Http response.
286
*/
287
abstract class HttpResponse implements Closeable {
288
/**
289
* Gets the response status code.
290
* @return HTTP status code
291
*/
292
public abstract int getStatusCode();
293
294
/**
295
* Lookup a response header with the provided name.
296
* @param name Header name (case-insensitive)
297
* @return Header value or null if not found
298
*/
299
public abstract String getHeaderValue(String name);
300
301
/**
302
* Gets all response headers.
303
* @return HttpHeaders containing all response headers
304
*/
305
public abstract HttpHeaders getHeaders();
306
307
/**
308
* Gets the response body as Flux of ByteBuffer.
309
* @return Response body as Flux
310
*/
311
public abstract Flux<ByteBuffer> getBody();
312
313
/**
314
* Gets the response body as BinaryData.
315
* @return Response body as BinaryData
316
*/
317
public abstract Mono<BinaryData> getBodyAsBinaryData();
318
319
/**
320
* Gets the response body as String.
321
* @return Response body as String
322
*/
323
public abstract Mono<String> getBodyAsString();
324
325
/**
326
* Gets the response body as String with specified charset.
327
* @param charset Character encoding
328
* @return Response body as String
329
*/
330
public abstract Mono<String> getBodyAsString(Charset charset);
331
332
/**
333
* Gets the response body as InputStream.
334
* @return Response body as InputStream
335
*/
336
public abstract Mono<InputStream> getBodyAsInputStream();
337
338
/**
339
* Gets the request that resulted in this response.
340
* @return HttpRequest that generated this response
341
*/
342
public abstract HttpRequest getRequest();
343
344
/**
345
* Closes any resources associated with this HttpResponse.
346
*/
347
@Override
348
public void close();
349
}
350
```
351
352
### HttpMethod
353
354
HTTP method enumeration and utilities.
355
356
```java { .api }
357
/**
358
* Represents the HTTP methods that can be used in a request.
359
*/
360
public enum HttpMethod {
361
/** The HTTP GET method. */
362
GET,
363
364
/** The HTTP PUT method. */
365
PUT,
366
367
/** The HTTP POST method. */
368
POST,
369
370
/** The HTTP PATCH method. */
371
PATCH,
372
373
/** The HTTP DELETE method. */
374
DELETE,
375
376
/** The HTTP HEAD method. */
377
HEAD,
378
379
/** The HTTP OPTIONS method. */
380
OPTIONS,
381
382
/** The HTTP TRACE method. */
383
TRACE,
384
385
/** The HTTP CONNECT method. */
386
CONNECT
387
}
388
```
389
390
### HttpHeaders
391
392
Collection for managing HTTP headers with case-insensitive names.
393
394
```java { .api }
395
/**
396
* A collection of headers on an HTTP request or response.
397
*/
398
class HttpHeaders implements Iterable<HttpHeader> {
399
/**
400
* Create an empty HttpHeaders instance.
401
*/
402
public HttpHeaders();
403
404
/**
405
* Create HttpHeaders with initial capacity.
406
* @param initialCapacity Initial capacity for headers map
407
*/
408
public HttpHeaders(int initialCapacity);
409
410
/**
411
* Create HttpHeaders from existing map.
412
* @param headers Map of header name-value pairs
413
*/
414
public HttpHeaders(Map<String, String> headers);
415
416
/**
417
* Gets the number of headers.
418
* @return Number of headers
419
*/
420
public int size();
421
422
/**
423
* Sets a header name-value pair.
424
* @param name Header name
425
* @param value Header value
426
* @return Updated HttpHeaders
427
*/
428
public HttpHeaders set(String name, String value);
429
430
/**
431
* Sets a header name-value pair.
432
* @param header HttpHeader to set
433
* @return Updated HttpHeaders
434
*/
435
public HttpHeaders set(HttpHeader header);
436
437
/**
438
* Adds a header name-value pair.
439
* @param name Header name
440
* @param value Header value
441
* @return Updated HttpHeaders
442
*/
443
public HttpHeaders add(String name, String value);
444
445
/**
446
* Adds a header.
447
* @param header HttpHeader to add
448
* @return Updated HttpHeaders
449
*/
450
public HttpHeaders add(HttpHeader header);
451
452
/**
453
* Gets the value of the header with the specified name.
454
* @param name Header name (case-insensitive)
455
* @return Header value or null if not found
456
*/
457
public String getValue(String name);
458
459
/**
460
* Gets all values for the header with the specified name.
461
* @param name Header name (case-insensitive)
462
* @return List of header values
463
*/
464
public List<String> getValues(String name);
465
466
/**
467
* Removes the header with the specified name.
468
* @param name Header name to remove
469
* @return Header value that was removed, or null
470
*/
471
public String remove(String name);
472
473
/**
474
* Gets all headers as a Map.
475
* @return Map of header name-value pairs
476
*/
477
public Map<String, String> toMap();
478
479
/**
480
* Gets an iterator over the headers.
481
* @return Iterator over HttpHeader instances
482
*/
483
@Override
484
public Iterator<HttpHeader> iterator();
485
486
/**
487
* Gets a stream of the headers.
488
* @return Stream of HttpHeader instances
489
*/
490
public Stream<HttpHeader> stream();
491
}
492
```
493
494
### HttpHeader
495
496
Individual HTTP header representation.
497
498
```java { .api }
499
/**
500
* Represents a single header within an HTTP request or response.
501
*/
502
class HttpHeader {
503
/**
504
* Create an HTTP header.
505
* @param name Header name
506
* @param value Header value
507
*/
508
public HttpHeader(String name, String value);
509
510
/**
511
* Create an HTTP header.
512
* @param name Header name
513
* @param values List of header values
514
*/
515
public HttpHeader(String name, List<String> values);
516
517
/**
518
* Gets the header name.
519
* @return Header name
520
*/
521
public String getName();
522
523
/**
524
* Gets the header value.
525
* @return Header value (comma-separated if multiple values)
526
*/
527
public String getValue();
528
529
/**
530
* Gets all header values.
531
* @return List of header values
532
*/
533
public List<String> getValues();
534
535
/**
536
* Gets the header as a string in the format "name: value".
537
* @return Header string representation
538
*/
539
@Override
540
public String toString();
541
}
542
```
543
544
### ContentType
545
546
HTTP content type representation and utilities.
547
548
```java { .api }
549
/**
550
* Represents the value of a Content-Type header as an HTTP header value.
551
*/
552
class ContentType {
553
/**
554
* Creates a ContentType from a content type string.
555
* @param contentType Content type string
556
* @return ContentType instance
557
*/
558
public static ContentType parse(String contentType);
559
560
/**
561
* Gets the media type (e.g., "application/json").
562
* @return Media type
563
*/
564
public String getType();
565
566
/**
567
* Gets the subtype (e.g., "json" from "application/json").
568
* @return Subtype
569
*/
570
public String getSubtype();
571
572
/**
573
* Gets the charset parameter.
574
* @return Charset or null if not specified
575
*/
576
public String getCharset();
577
578
/**
579
* Gets a parameter value.
580
* @param parameterName Parameter name
581
* @return Parameter value or null
582
*/
583
public String getParameter(String parameterName);
584
585
/**
586
* Gets all parameters.
587
* @return Map of parameter name-value pairs
588
*/
589
public Map<String, String> getParameters();
590
591
/**
592
* Converts to content type string.
593
* @return Content type string
594
*/
595
@Override
596
public String toString();
597
}
598
```
599
600
### HttpHeaderName
601
602
HTTP header name constants and utilities with case-insensitive comparison.
603
604
```java { .api }
605
/**
606
* Represents HTTP header names for multiple versions of HTTP.
607
*/
608
class HttpHeaderName extends ExpandableStringEnum<HttpHeaderName> {
609
/**
610
* Gets or creates the HttpHeaderName for the passed name.
611
* @param name The name
612
* @return The HttpHeaderName of the passed name, or null if name was null
613
*/
614
public static HttpHeaderName fromString(String name);
615
616
/**
617
* Gets the HTTP header name based on the name passed into fromString.
618
* @return The HTTP header name based on the construction of this HttpHeaderName
619
*/
620
public String getCaseSensitiveName();
621
622
/**
623
* Gets the HTTP header name lower cased.
624
* @return The HTTP header name lower cased
625
*/
626
public String getCaseInsensitiveName();
627
628
// Common header name constants
629
public static final HttpHeaderName ACCEPT = fromString("Accept");
630
public static final HttpHeaderName AUTHORIZATION = fromString("Authorization");
631
public static final HttpHeaderName CONTENT_TYPE = fromString("Content-Type");
632
public static final HttpHeaderName CONTENT_LENGTH = fromString("Content-Length");
633
public static final HttpHeaderName USER_AGENT = fromString("User-Agent");
634
public static final HttpHeaderName CACHE_CONTROL = fromString("Cache-Control");
635
public static final HttpHeaderName ETAG = fromString("ETag");
636
public static final HttpHeaderName IF_MATCH = fromString("If-Match");
637
public static final HttpHeaderName IF_NONE_MATCH = fromString("If-None-Match");
638
public static final HttpHeaderName LAST_MODIFIED = fromString("Last-Modified");
639
public static final HttpHeaderName LOCATION = fromString("Location");
640
public static final HttpHeaderName RETRY_AFTER = fromString("Retry-After");
641
public static final HttpHeaderName DATE = fromString("Date");
642
public static final HttpHeaderName HOST = fromString("Host");
643
public static final HttpHeaderName X_MS_CLIENT_REQUEST_ID = fromString("x-ms-client-request-id");
644
public static final HttpHeaderName X_MS_REQUEST_ID = fromString("x-ms-request-id");
645
public static final HttpHeaderName TRACEPARENT = fromString("traceparent");
646
}
647
```
648
649
### RestProxy
650
651
Factory for creating REST API clients from annotated interfaces.
652
653
```java { .api }
654
/**
655
* Type to create a proxy implementation for an interface describing REST API methods.
656
*/
657
class RestProxy {
658
/**
659
* Create a proxy implementation of the provided Swagger interface.
660
* @param <A> Swagger interface type
661
* @param swaggerInterface Swagger interface to implement
662
* @param httpPipeline HTTP pipeline for requests
663
* @return Proxy implementation
664
*/
665
public static <A> A create(Class<A> swaggerInterface, HttpPipeline httpPipeline);
666
667
/**
668
* Create a proxy implementation of the provided Swagger interface.
669
* @param <A> Swagger interface type
670
* @param swaggerInterface Swagger interface to implement
671
* @param httpPipeline HTTP pipeline for requests
672
* @param serializer Serializer for request/response bodies
673
* @return Proxy implementation
674
*/
675
public static <A> A create(Class<A> swaggerInterface, HttpPipeline httpPipeline,
676
SerializerAdapter serializer);
677
}
678
```
679
680
## Usage Examples
681
682
### Creating HTTP Pipeline
683
684
```java
685
import com.azure.core.http.*;
686
import com.azure.core.http.policy.*;
687
import com.azure.core.credential.TokenCredential;
688
689
// Create pipeline with authentication and retry
690
TokenCredential credential = // ... get credential
691
HttpPipeline pipeline = new HttpPipelineBuilder()
692
.httpClient(HttpClient.createDefault())
693
.policies(
694
new UserAgentPolicy("MyApp/1.0"),
695
new BearerTokenAuthenticationPolicy(credential, "https://vault.azure.net/.default"),
696
new RetryPolicy(new RetryOptions()),
697
new HttpLoggingPolicy(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BASIC))
698
)
699
.build();
700
```
701
702
### Sending HTTP Requests
703
704
```java
705
import com.azure.core.http.*;
706
import com.azure.core.util.BinaryData;
707
import com.azure.core.util.Context;
708
709
// Create and configure request
710
HttpRequest request = new HttpRequest(HttpMethod.POST, "https://api.example.com/users");
711
request.setHeader("Content-Type", "application/json");
712
request.setHeader("Accept", "application/json");
713
714
// Set JSON body
715
String jsonBody = "{\"name\":\"John\",\"email\":\"john@example.com\"}";
716
request.setBody(BinaryData.fromString(jsonBody));
717
718
// Send request through pipeline
719
HttpResponse response = pipeline.send(request, Context.NONE).block();
720
721
// Handle response
722
if (response.getStatusCode() == 201) {
723
BinaryData responseBody = response.getBodyAsBinaryData().block();
724
String responseJson = responseBody.toString();
725
System.out.println("Created user: " + responseJson);
726
} else {
727
System.out.println("Request failed with status: " + response.getStatusCode());
728
}
729
```
730
731
### Using REST Proxy
732
733
```java
734
import com.azure.core.annotation.*;
735
import com.azure.core.http.rest.Response;
736
import com.azure.core.util.Context;
737
import reactor.core.publisher.Mono;
738
739
// Define REST API interface
740
@ServiceInterface(name = "UserService")
741
interface UserServiceClient {
742
@Get("/users/{userId}")
743
@ExpectedResponses({200})
744
Mono<Response<User>> getUser(@PathParam("userId") String userId);
745
746
@Post("/users")
747
@ExpectedResponses({201})
748
Mono<Response<User>> createUser(@BodyParam("application/json") User user);
749
}
750
751
// Create client using REST proxy
752
UserServiceClient client = RestProxy.create(UserServiceClient.class, pipeline);
753
754
// Use the client
755
User newUser = new User("John", "john@example.com");
756
Response<User> response = client.createUser(newUser).block();
757
User createdUser = response.getValue();
758
```