The technical principles and application practice of Apache httpclient Fluent API
1. Send GET request:
String responseBody = Request.Get("https://api.example.com/data")
.connectTimeout(5000)
.socketTimeout(5000)
.execute()
.returnContent()
.asString();
System.out.println(responseBody);
2. Send post request and pass the number of forms:
HttpResponse response = Request.Post("https://api.example.com/submit")
.bodyForm(Form.form()
.add("username", "john")
.add("password", "p@ssw0rd")
.build())
.execute()
.returnResponse();
int statusCode = response.getStatusLine().getStatusCode();
System.out.println("Status code: " + statusCode);
3. Put request with a request header:
String requestBody = "{\"name\": \"John\", \"age\": 25}";
String responseBody = Request.Put("https://api.example.com/update")
.addHeader("Authorization", "Bearer token")
.bodyString(requestBody, ContentType.APPLICATION_JSON)
.execute()
.returnContent()
.asString();
System.out.println(responseBody);
In summary, Apache HTTPClient Fluent API provides a simple, elegant, and easy -to -use way to build HTTP requests so that developers can interact more efficiently with Web services.Its design principle is based on the builder mode and streaming calls. The chain calls can easily set the request parameters.Whether it is sending GET requests, post requests or other types of HTTP requests, Apache HTTPClient Fluent API can meet various usage scenarios and greatly simplify the process of request construction.