0
# HTTP Client
1
2
The HTTP client system provides lightweight, blocking HTTP communication capabilities designed specifically for dashboard communication. It supports GET and POST requests with form-encoded parameters and includes comprehensive response parsing.
3
4
## Capabilities
5
6
### SimpleHttpClient
7
8
Main HTTP client implementation that provides blocking, synchronous HTTP requests.
9
10
```java { .api }
11
/**
12
* A very simple HTTP client that only supports GET/POST method and plain text request body.
13
* The Content-Type header is always set as application/x-www-form-urlencoded.
14
* All parameters in the request will be encoded using URLEncoder.encode(String, String).
15
*
16
* The result of a HTTP invocation will be wrapped as a SimpleHttpResponse. Content in response body
17
* will be automatically decoded to string with provided charset.
18
*
19
* This is a blocking and synchronous client, so an invocation will await the response until timeout exceed.
20
*
21
* Note that this is a very NAIVE client, Content-Length must be specified in the
22
* HTTP response header, otherwise, the response body will be dropped. All other body type such as
23
* Transfer-Encoding: chunked, Transfer-Encoding: deflate are not supported.
24
*/
25
public class SimpleHttpClient {
26
27
/**
28
* Execute a GET HTTP request.
29
* @param request HTTP request configuration
30
* @return the response if the request is successful
31
* @throws IOException when connection cannot be established or the connection is interrupted
32
*/
33
public SimpleHttpResponse get(SimpleHttpRequest request) throws IOException;
34
35
/**
36
* Execute a POST HTTP request.
37
* @param request HTTP request configuration
38
* @return the response if the request is successful
39
* @throws IOException when connection cannot be established or the connection is interrupted
40
*/
41
public SimpleHttpResponse post(SimpleHttpRequest request) throws IOException;
42
}
43
```
44
45
**Usage Examples:**
46
47
```java
48
import com.alibaba.csp.sentinel.transport.heartbeat.client.SimpleHttpClient;
49
import com.alibaba.csp.sentinel.transport.heartbeat.client.SimpleHttpRequest;
50
import com.alibaba.csp.sentinel.transport.heartbeat.client.SimpleHttpResponse;
51
import com.alibaba.csp.sentinel.transport.endpoint.Endpoint;
52
import com.alibaba.csp.sentinel.transport.endpoint.Protocol;
53
54
// Create HTTP client
55
SimpleHttpClient client = new SimpleHttpClient();
56
57
// Create endpoint for dashboard server
58
Endpoint endpoint = new Endpoint(Protocol.HTTP, "dashboard.example.com", 8080);
59
60
// GET request example
61
SimpleHttpRequest getRequest = new SimpleHttpRequest(endpoint, "/api/status");
62
getRequest.addParam("app", "my-application");
63
getRequest.addParam("type", "health");
64
65
try {
66
SimpleHttpResponse response = client.get(getRequest);
67
System.out.println("Status: " + response.getStatusCode());
68
System.out.println("Body: " + response.getBodyAsString());
69
} catch (IOException e) {
70
System.err.println("Request failed: " + e.getMessage());
71
}
72
73
// POST request example
74
SimpleHttpRequest postRequest = new SimpleHttpRequest(endpoint, "/api/heartbeat");
75
postRequest.addParam("hostname", "web-server-01");
76
postRequest.addParam("ip", "192.168.1.100");
77
postRequest.addParam("port", "8719");
78
postRequest.setSoTimeout(5000); // 5 second timeout
79
80
SimpleHttpResponse postResponse = client.post(postRequest);
81
if (postResponse.getStatusCode() == 200) {
82
System.out.println("Heartbeat successful");
83
}
84
```
85
86
### SimpleHttpRequest
87
88
HTTP request configuration with builder-style methods for setting parameters and options.
89
90
```java { .api }
91
/**
92
* Simple HTTP request representation.
93
*/
94
public class SimpleHttpRequest {
95
96
/**
97
* Constructor with endpoint and request path
98
* @param endpoint target server endpoint
99
* @param requestPath path component of the URL
100
*/
101
public SimpleHttpRequest(Endpoint endpoint, String requestPath);
102
103
/**
104
* Get the target endpoint
105
* @return endpoint configuration
106
*/
107
public Endpoint getEndpoint();
108
109
/**
110
* Set the target endpoint
111
* @param endpoint target server endpoint
112
* @return this request for method chaining
113
*/
114
public SimpleHttpRequest setEndpoint(Endpoint endpoint);
115
116
/**
117
* Get the request path
118
* @return URL path component
119
*/
120
public String getRequestPath();
121
122
/**
123
* Set the request path
124
* @param requestPath URL path component
125
* @return this request for method chaining
126
*/
127
public SimpleHttpRequest setRequestPath(String requestPath);
128
129
/**
130
* Get socket timeout in milliseconds
131
* @return timeout value (default: 3000ms)
132
*/
133
public int getSoTimeout();
134
135
/**
136
* Set socket timeout in milliseconds
137
* @param soTimeout timeout for socket operations
138
* @return this request for method chaining
139
*/
140
public SimpleHttpRequest setSoTimeout(int soTimeout);
141
142
/**
143
* Get all request parameters
144
* @return map of parameter key-value pairs
145
*/
146
public Map<String, String> getParams();
147
148
/**
149
* Set all request parameters
150
* @param params map of parameter key-value pairs
151
* @return this request for method chaining
152
*/
153
public SimpleHttpRequest setParams(Map<String, String> params);
154
155
/**
156
* Get request charset
157
* @return charset for encoding parameters (default: from SentinelConfig)
158
*/
159
public Charset getCharset();
160
161
/**
162
* Set request charset
163
* @param charset charset for encoding parameters
164
* @return this request for method chaining
165
*/
166
public SimpleHttpRequest setCharset(Charset charset);
167
168
/**
169
* Add a single parameter to the request
170
* @param key parameter name (cannot be empty)
171
* @param value parameter value
172
* @return this request for method chaining
173
* @throws IllegalArgumentException if key is blank
174
*/
175
public SimpleHttpRequest addParam(String key, String value);
176
}
177
```
178
179
### SimpleHttpResponse
180
181
HTTP response representation providing access to status, headers, and body content.
182
183
```java { .api }
184
/**
185
* Simple HTTP response representation.
186
*/
187
public class SimpleHttpResponse {
188
189
/**
190
* Constructor for response without body
191
* @param statusLine HTTP status line (e.g., "HTTP/1.1 200 OK")
192
* @param headers response headers
193
*/
194
public SimpleHttpResponse(String statusLine, Map<String, String> headers);
195
196
/**
197
* Constructor for response with body
198
* @param statusLine HTTP status line
199
* @param headers response headers
200
* @param body response body as bytes
201
*/
202
public SimpleHttpResponse(String statusLine, Map<String, String> headers, byte[] body);
203
204
/**
205
* Set response body
206
* @param body response body as bytes
207
*/
208
public void setBody(byte[] body);
209
210
/**
211
* Get response body as raw bytes
212
* @return body bytes, or null if no body
213
*/
214
public byte[] getBody();
215
216
/**
217
* Get HTTP status line
218
* @return full status line (e.g., "HTTP/1.1 200 OK")
219
*/
220
public String getStatusLine();
221
222
/**
223
* Get HTTP status code
224
* @return numeric status code (e.g., 200, 404)
225
*/
226
public Integer getStatusCode();
227
228
/**
229
* Get all response headers
230
* @return map of header name-value pairs
231
*/
232
public Map<String, String> getHeaders();
233
234
/**
235
* Get specific header value (case-insensitive lookup)
236
* First tries exact match, then falls back to case-insensitive search
237
* @param key header name
238
* @return header value, or null if not found
239
*/
240
public String getHeader(String key);
241
242
/**
243
* Get response body as string with appropriate charset parsing.
244
* Automatically detects charset from Content-Type header or uses default.
245
* @return body content as string using detected or default charset
246
*/
247
public String getBodyAsString();
248
249
/**
250
* String representation of entire response
251
* @return formatted response with status, headers, and body
252
*/
253
public String toString();
254
}
255
```
256
257
### SimpleHttpResponseParser
258
259
Parser for converting raw HTTP response streams into SimpleHttpResponse objects.
260
261
```java { .api }
262
/**
263
* The parser provides functionality to parse raw bytes HTTP response to a SimpleHttpResponse.
264
*
265
* Note that this is a very NAIVE parser, Content-Length must be specified in the
266
* HTTP response header, otherwise, the body will be dropped. All other body type such as
267
* Transfer-Encoding: chunked, Transfer-Encoding: deflate are not supported.
268
*/
269
public class SimpleHttpResponseParser {
270
private static final int MAX_BODY_SIZE = 1024 * 1024 * 4; // 4MB limit
271
272
/**
273
* Default constructor with 4KB buffer
274
*/
275
public SimpleHttpResponseParser();
276
277
/**
278
* Constructor with custom buffer size
279
* @param maxSize maximum buffer size for parsing (must be > 0)
280
* @throws IllegalArgumentException if maxSize < 0
281
*/
282
public SimpleHttpResponseParser(int maxSize);
283
284
/**
285
* Parse bytes from an input stream to a SimpleHttpResponse
286
* @param in input stream from socket connection
287
* @return parsed HTTP response entity
288
* @throws IOException when an IO error occurs
289
* @throws IllegalStateException when response body is too large or content length is invalid
290
* @throws IndexOutOfBoundsException when buffer size is exceeded during parsing
291
*/
292
public SimpleHttpResponse parse(InputStream in) throws IOException;
293
}
294
```
295
296
### SocketFactory
297
298
Factory for creating sockets based on protocol requirements (HTTP vs HTTPS).
299
300
```java { .api }
301
/**
302
* Factory for creating sockets based on protocol type
303
*/
304
public class SocketFactory {
305
306
/**
307
* Get socket for specified protocol
308
* @param protocol HTTP or HTTPS protocol
309
* @return Socket for HTTP, SSLSocket for HTTPS
310
* @throws IOException if socket creation fails
311
*/
312
public static Socket getSocket(Protocol protocol) throws IOException;
313
}
314
```
315
316
## Protocol Support
317
318
**HTTP Support:**
319
- Standard TCP sockets for HTTP connections
320
- Port-based connections to dashboard servers
321
- Form-encoded parameter transmission
322
323
**HTTPS Support:**
324
- SSL/TLS socket connections via SSLSocketFactory
325
- Certificate validation through SslFactory configuration
326
- Secure communication with HTTPS dashboard endpoints
327
328
## Request Processing
329
330
**Parameter Encoding:**
331
- All parameters URL-encoded using UTF-8 (or configured charset)
332
- Form-encoded content type: `application/x-www-form-urlencoded`
333
- GET parameters added to query string
334
- POST parameters sent in request body
335
336
**Request Format:**
337
```
338
POST /api/endpoint HTTP/1.1
339
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
340
Host: dashboard.example.com
341
Content-Length: 45
342
343
param1=value1¶m2=value2¶m3=value3
344
```
345
346
**Response Requirements:**
347
- Content-Length header required for body parsing
348
- Response body limited to 4MB maximum
349
- UTF-8 charset assumed unless specified in Content-Type
350
351
## Error Handling
352
353
The HTTP client handles errors at multiple levels:
354
355
**Connection Errors:**
356
- IOException thrown for network connectivity issues
357
- Socket timeout exceptions for unresponsive servers
358
- Connection refused for unavailable endpoints
359
360
**Protocol Errors:**
361
- Malformed HTTP responses logged and cause IOException
362
- Missing Content-Length results in empty response body
363
- Invalid character encoding uses default charset
364
365
**Response Size Limits:**
366
- Maximum response body size: 4MB
367
- Buffer overflow protection in response parser
368
- Large responses automatically truncated with logging