Use Core :: http client framework to make network requests in the Java class library
Use Core :: http client framework to make network requests in the Java class library
In Java development, network requests are very common operations.In order to simplify and facilitate network requests, the Java class library provides many different frameworks and libraries.One of the very effective and popular frameworks is Core :: HTTP client framework.
Core :: HTTP client framework is a powerful HTTP client library. It provides a simple and flexible way to execute HTTP requests and process response data.It supports various HTTP methods (such as GET, POST, PUT, etc.), as well as various HTTP head information and parameter settings.
The following is an example code that shows how to use Core :: http client framework for network requests:
import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.classic.methods.HttpPost;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.core5.http.HttpEntity;
import org.apache.hc.core5.http.ParseException;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import java.io.IOException;
public class HttpClientExample {
public static void main(String[] args) {
CloseableHttpClient httpClient = HttpClients.createDefault();
// Send GET request
HttpGet httpGet = new HttpGet("http://www.example.com");
try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
HttpEntity entity = response.getEntity();
String result = EntityUtils.toString(entity);
System.out.println(result);
EntityUtils.consume(entity);
} catch (IOException | ParseException e) {
e.printStackTrace();
}
// Send post request
HttpPost httpPost = new HttpPost("http://www.example.com");
try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
HttpEntity entity = response.getEntity();
String result = EntityUtils.toString(entity);
System.out.println(result);
EntityUtils.consume(entity);
} catch (IOException | ParseException e) {
e.printStackTrace();
} finally {
try {
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
In the above code example, we first created an `CloseablehttpClient` object to execute HTTP requests.Then, we created a `httpget` instance, set the requested URL, and use the` httpClient.execute (httpget) method to send a GET request and get the response data.Similarly, we also demonstrated how to send post requests.
Core :: HTTP client framework for network requests is very simple and has many functions and configuration options.By using this framework, we can easily interact with Web services to obtain and process the returned data.Whether it is a simple GET request or a more complicated Post request, Core :: HTTP client framework can meet our needs.