1. Importing the HttpClient Dependency
First, confirm whether the HttpClient dependency has been included in the project. If it has not been included, add the following code to the pom.xml to import the HttpClient dependency:
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.13</version>
</dependency>
2. Sending GET Requests
2.1 Sending GET Requests (No Parameters)
import org.apache.http.HttpStatus;
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;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
public class HttpClientUtils {
public static String doGet() throws IOException {
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
HttpGet httpGet = new HttpGet("https://www.example.com/getDataList");
try (CloseableHttpResponse httpResponse = httpClient.execute(httpGet)) {
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
return EntityUtils.toString(httpResponse.getEntity(), StandardCharsets.UTF_8);
}
return null;
}
}
}
}
2.2 Sending GET Requests (With Parameters)
The first method is to directly concatenate parameters to the URL, as shown below:
HttpGet httpGet = new HttpGet("https://www.example.com/getDataList?pageIndex=1&pageSize=20");
The second method is to use URIBuilder to add parameters, as shown below:
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
public class HttpClientUtils {
public static String doGet() throws IOException, URISyntaxException {
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
URIBuilder uriBuilder = new URIBuilder("https://www.example.com/getDataList");
uriBuilder.addParameter("pageIndex", "1");
uriBuilder.addParameter("pageSize", "20");
HttpGet httpGet = new HttpGet(uriBuilder.build());
try (CloseableHttpResponse httpResponse = httpClient.execute(httpGet)) {
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
return EntityUtils.toString(httpResponse.getEntity(), StandardCharsets.UTF_8);
}
return null;
}
}
}
}
3. Sending POST Requests
3.1 Sending POST Requests (No Parameters)
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
public class HttpClientUtils {
public static String doPost() throws IOException {
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
HttpPost httpPost = new HttpPost("https://www.example.com/updateData");
try (CloseableHttpResponse httpResponse = httpClient.execute(httpPost)) {
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
return EntityUtils.toString(httpResponse.getEntity(), StandardCharsets.UTF_8);
}
return null;
}
}
}
}
3.2 Sending POST Requests (With Parameters, Form Submission)
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
public class HttpClientUtils {
public static String doPost() throws IOException {
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
HttpPost httpPost = new HttpPost("https://www.example.com/updateData");
List<namevaluepair> params = new ArrayList<>();
params.add(new BasicNameValuePair("id", "1"));
params.add(new BasicNameValuePair("name", "New Name"));
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(params, StandardCharsets.UTF_8);
httpPost.setEntity(formEntity);
try (CloseableHttpResponse httpResponse = httpClient.execute(httpPost)) {
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
return EntityUtils.toString(httpResponse.getEntity(), StandardCharsets.UTF_8);
}
return null;
}
}
}
}
</namevaluepair>
3.3 Sending POST Requests (With Parameters, JSON Format)
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
public class HttpClientUtils {
public static String doPost() throws IOException {
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
HttpPost httpPost = new HttpPost("https://www.example.com/updateData");
String jsonBody = "{\"id\":\"1\",\"name\":\"New Name\"}";
StringEntity stringEntity = new StringEntity(jsonBody);
stringEntity.setContentType("application/json;charset=utf-8");
httpPost.setEntity(stringEntity);
try (CloseableHttpResponse httpResponse = httpClient.execute(httpPost)) {
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
return EntityUtils.toString(httpResponse.getEntity(), StandardCharsets.UTF_8);
}
return null;
}
}
}
}
4. Sending PUT Requests
4.1 Sending PUT Requests (No Parameters)
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
public class HttpClientUtils {
public static String doPut() throws IOException {
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
HttpPut httpPut = new HttpPut("https://www.example.com/updateData");
try (CloseableHttpResponse httpResponse = httpClient.execute(httpPut)) {
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
return EntityUtils.toString(httpResponse.getEntity(), StandardCharsets.UTF_8);
}
return null;
}
}
}
}
4.2 Sending PUT Requests (With Parameters, Form Submission)
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
public class HttpClientUtils {
public static String doPut() throws IOException {
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
HttpPut httpPut = new HttpPut("https://www.example.com/updateData");
List<namevaluepair> params = new ArrayList<>();
params.add(new BasicNameValuePair("id", "1"));
params.add(new BasicNameValuePair("name", "New Name"));
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(params, StandardCharsets.UTF_8);
httpPut.setEntity(formEntity);
try (CloseableHttpResponse httpResponse = httpClient.execute(httpPut)) {
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
return EntityUtils.toString(httpResponse.getEntity(), StandardCharsets.UTF_8);
}
return null;
}
}
}
}
</namevaluepair>
4.3 Sending PUT Requests (With Parameters, JSON Format)
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
public class HttpClientUtils {
public static String doPut() throws IOException {
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
HttpPut httpPut = new HttpPut("https://www.example.com/updateData");
String jsonBody = "{\"id\":\"1\",\"name\":\"New Name\"}";
StringEntity stringEntity = new StringEntity(jsonBody);
stringEntity.setContentType("application/json;charset=utf-8");
httpPut.setEntity(stringEntity);
try (CloseableHttpResponse httpResponse = httpClient.execute(httpPut)) {
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
return EntityUtils.toString(httpResponse.getEntity(), StandardCharsets.UTF_8);
}
return null;
}
}
}
}
5. Sending DELETE Requests
5.1 Sending DELETE Requests (No Parameters)
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
public class HttpClientUtils {
public static String doDelete() throws IOException {
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
HttpDelete httpDelete = new HttpDelete("https://www.example.com/updateData");
try (CloseableHttpResponse httpResponse = httpClient.execute(httpDelete)) {
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
return EntityUtils.toString(httpResponse.getEntity(), StandardCharsets.UTF_8);
}
return null;
}
}
}
}
6. Adding Request Headers
Generally, when requesting third-party interfaces, it is necessary to include headers such as signatures and timestamps. For example, to add headers in a POST request, the code is as follows:
httpPost.setHeader("Content-Type", "application/json;charset=utf-8");
httpPost.setHeader("signature", "3045022100875efcef9eb54626bb0168a6baa7c61265d0001d49243f");
httpPost.setHeader("timestamp", String.valueOf(System.currentTimeMillis()));
The method for adding headers in GET, PUT, and DELETE requests is the same as above.
7. Setting Timeout
If you need to customize the connection timeout and data transfer timeout for HTTP requests, the code is as follows (using POST request as an example):
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(5000)
.setSocketTimeout(10000)
.build();
httpPost.setConfig(requestConfig);
The method for setting timeout in GET, PUT, and DELETE requests is the same as above.
8. Utility Class Encapsulation
The complete utility class code is as follows:
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class HttpClientUtils {
/**
* Connection establishment timeout (unit: milliseconds)
*/
private static final int CONNECT_TIMEOUT = 5000;
/**
* Data transfer timeout (unit: milliseconds)
*/
private static final int SOCKET_TIMEOUT = 10000;
/**
* Execute GET request
*
* @param url Request URL
* @param headers Request headers
* @return Response content string
*/
public static String doGet(String url, Map<string, string=""> headers) throws IOException {
HttpGet httpGet = new HttpGet(url);
// Set request headers
setHeaders(httpGet, headers);
return executeRequest(httpGet);
}
/**
* Execute GET request
*
* @param url Request URL
* @param headers Request headers
* @param params Request parameters
* @return Response content string
*/
public static String doGet(String url, Map<string, string=""> headers, Map<string, string=""> params) throws IOException, URISyntaxException {
URIBuilder uriBuilder = new URIBuilder(url);
// Set request parameters
if (params != null && !params.isEmpty()) {
for (Map.Entry<string, string=""> entry : params.entrySet()) {
uriBuilder.setParameter(entry.getKey(), entry.getValue());
}
}
HttpGet httpGet = new HttpGet(uriBuilder.build());
// Set request headers
setHeaders(httpGet, headers);
return executeRequest(httpGet);
}
/**
* Execute POST request (form submission)
*
* @param url Request URL
* @return Response content string
*/
public static String doPost(String url) throws IOException {
return doPost(url, null, null);
}
/**
* Execute POST request (form submission)
*
* @param url Request URL
* @param headers Request headers
* @return Response content string
*/
public static String doPost(String url, Map<string, string=""> headers) throws IOException {
return doPost(url, headers, null);
}
/**
* Execute POST request (form submission)
*
* @param url Request URL
* @param headers Request headers
* @param params Request parameters
* @return Response content string
*/
public static String doPost(String url, Map<string, string=""> headers, Map<string, string=""> params) throws IOException {
HttpPost httpPost = new HttpPost(url);
// Set request headers
setHeaders(httpPost, headers);
// Build form parameters
if (params != null) {
List<namevaluepair> paramList = new ArrayList<>();
for (Map.Entry<string, string=""> entry : params.entrySet()) {
paramList.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
httpPost.setEntity(new UrlEncodedFormEntity(paramList, StandardCharsets.UTF_8));
}
return executeRequest(httpPost);
}
/**
* Execute POST request (JSON format)
*
* @param url Request URL
* @param headers Request headers
* @return Response content string
*/
public static String doPostJson(String url, Map<string, string=""> headers) throws IOException {
return doPostJson(url, headers, null);
}
/**
* Execute POST request (JSON format)
*
* @param url Request URL
* @param headers Request headers
* @param jsonBody JSON request body string
* @return Response content string
*/
public static String doPostJson(String url, Map<string, string=""> headers, String jsonBody) throws IOException {
HttpPost httpPost = new HttpPost(url);
// Add JSON request header
addJsonHeader(httpPost, headers);
// Add custom request headers
setHeaders(httpPost, headers);
// Set JSON request body
if (jsonBody != null) {
StringEntity entity = new StringEntity(jsonBody,
ContentType.APPLICATION_JSON.withCharset(StandardCharsets.UTF_8));
httpPost.setEntity(entity);
}
return executeRequest(httpPost);
}
/**
* Execute PUT request (JSON format)
*
* @param url Request URL
* @param headers Request headers
* @param jsonBody JSON request body string
* @return Response content string
*/
public static String doPut(String url, Map<string, string=""> headers, String jsonBody) throws IOException {
HttpPut httpPut = new HttpPut(url);
// Add JSON request header
addJsonHeader(httpPut, headers);
// Add custom request headers
setHeaders(httpPut, headers);
// Set JSON request body
if (jsonBody != null) {
StringEntity entity = new StringEntity(jsonBody,
ContentType.APPLICATION_JSON.withCharset(StandardCharsets.UTF_8));
httpPut.setEntity(entity);
}
return executeRequest(httpPut);
}
/**
* Execute DELETE request
*
* @param url Request URL
* @param headers Request headers
* @return Response content string
*/
public static String doDelete(String url, Map<string, string=""> headers) throws IOException {
HttpDelete httpDelete = new HttpDelete(url);
// Set request headers
setHeaders(httpDelete, headers);
return executeRequest(httpDelete);
}
/**
* Create HttpClient with timeout configuration
*
* @return HttpClient instance
*/
private static CloseableHttpClient createHttpClient() {
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(CONNECT_TIMEOUT)
.setSocketTimeout(SOCKET_TIMEOUT)
.build();
return HttpClients.custom()
.setDefaultRequestConfig(requestConfig)
.build();
}
/**
* Add JSON request header
*
* @param httpRequest HTTP request object
* @param headers Request headers
*/
private static void addJsonHeader(HttpRequestBase httpRequest, Map<string, string=""> headers) {
if (headers == null || !headers.containsKey("Content-Type")) {
httpRequest.addHeader("Content-Type", "application/json;charset=utf-8");
}
}
/**
* Set request headers
*
* @param httpRequest HTTP request object
* @param headers Request headers
*/
private static void setHeaders(HttpRequestBase httpRequest, Map<string, string=""> headers) {
if (headers == null || headers.isEmpty()) {
return;
}
for (Map.Entry<string, string=""> entry : headers.entrySet()) {
httpRequest.setHeader(entry.getKey(), entry.getValue());
}
}
/**
* Unified execution of requests and handling responses
*
* @param httpRequest HTTP request object
* @return Response content string
*/
private static String executeRequest(HttpRequestBase httpRequest) throws IOException {
try (CloseableHttpClient httpClient = createHttpClient()) {
try (CloseableHttpResponse response = httpClient.execute(httpRequest)) {
return handleResponse(response);
}
}
}
/**
* Handle response results
*
* @param response HTTP response object
* @return Response content string
*/
private static String handleResponse(CloseableHttpResponse response) throws IOException {
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
throw new RuntimeException("HTTP request failed, status code: " + statusCode);
}
HttpEntity entity = response.getEntity();
if (entity != null) {
return EntityUtils.toString(entity, StandardCharsets.UTF_8);
}
return null;
}
}
</string,></string,></string,></string,></string,></string,></string,></string,></namevaluepair></string,></string,></string,></string,></string,></string,></string,>