Core :: http client framework in the Java class library
Core :: HTTP client framework is a class library for processing HTTP requests and response in the Java program.It provides a set of simple and easy -to -use APIs that encapsulate the complexity related to HTTP communication, allowing developers to quickly conduct HTTP communication.
Core :: HTTP client framework work principle is as follows:
1. Create an HTTP client object: First of all, we need to create an HTTP client object, which is responsible for establishing a connection with the server and processing the HTTP request and response.
CloseableHttpClient httpClient = HttpClients.createDefault();
2. Create an HTTP request object: Next, we can create a HTTP request object to specify the method, URL, head information, etc. to specify the HTTP request to be sent.
HttpGet httpGetRequest = new HttpGet("https://example.com/api/users");
3. Send HTTP request: Use the HTTP client object to send the HTTP request and get the server's response.
CloseableHttpResponse response = httpClient.execute(httpGetRequest);
4. Processing server response: Once the server response is received, we can obtain the response status code, head information and response body through the HTTP response object.
int statusCode = response.getStatusLine().getStatusCode();
Header[] headers = response.getAllHeaders();
String responseBody = EntityUtils.toString(response.getEntity());
5. Close HTTP connection: After completing all HTTP communication, in order to release resources, we need to close the HTTP connection.
response.close();
httpClient.close();
This is a simple example of using core :: http client framework to send GET requests:
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
public class HttpClientExample {
public static void main(String[] args) {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpGet httpGetRequest = new HttpGet("https://example.com/api/users");
try {
CloseableHttpResponse response = httpClient.execute(httpGetRequest);
int statusCode = response.getStatusLine().getStatusCode();
String responseBody = EntityUtils.toString(response.getEntity());
System.out.println("Status Code: " + statusCode);
System.out.println("Response Body: " + responseBody);
response.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
httpClient.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
Through the above steps, we can easily use Core :: HTTP client framework to send HTTP requests and process server responses, simplifying the development process of HTTP communication.