Using Apache HttpClient for HTTP requests in Java API development
With the continuous development of the Internet, the HTTP protocol has become one of the cornerstones of modern network communication. In Java programming, by using the Apache HttpClient library, you can perform HTTP request operations very conveniently. This article will introduce how to use Apache HttpClient to make HTTP requests in Java API development.
- Preparation
Before you start, you need to download the Apache HttpClient library and add it as a dependency of the project. Apache HttpClient is an open source Java HTTP client library that can be referenced through tools such as Maven and Gradle.
The following is an example of using Maven to reference Apache HttpClient:
<dependencies> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.13</version> </dependency> </dependencies>
After introducing the library, you can start HTTP request operations.
- Send a GET request
Sending a GET request using HttpClient is very simple. The following is an example that demonstrates how to send a GET request through HttpClient and print out the response content:
CloseableHttpClient httpClient = HttpClients.createDefault(); HttpGet httpGet = new HttpGet("https://www.baidu.com"); try (CloseableHttpResponse response = httpClient.execute(httpGet)) { HttpEntity entity = response.getEntity(); if (entity != null) { String result = EntityUtils.toString(entity, "UTF-8"); System.out.println(result); } } catch (IOException e) { e.printStackTrace(); }
The above code will send a GET request to Baidu and then output the response content. In this code, we create a CloseableHttpClient client instance, then create a GET request using the HttpGet object, and execute the request. The entity is obtained in the response, and then the entity is converted into a string and output.
- Send a POST request
When using HttpClient to send a POST request, you can choose to use a UrlEncodedFormEntity object or a MultipartEntityBuilder object to include the request parameters.
The following is an example of using the UrlEncodedFormEntity object:
CloseableHttpClient httpClient = HttpClients.createDefault(); HttpPost httpPost = new HttpPost("https://www.baidu.com"); List<NameValuePair> params = new ArrayList<>(); params.add(new BasicNameValuePair("username", "johndoe")); params.add(new BasicNameValuePair("password", "password123")); try { httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8")); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } try (CloseableHttpResponse response = httpClient.execute(httpPost)) { HttpEntity entity = response.getEntity(); if (entity != null) { String result = EntityUtils.toString(entity, "UTF-8"); System.out.println(result); } } catch (IOException e) { e.printStackTrace(); }
The above code will send a POST request to Baidu and include the parameters in the request body. In this example, we use a UrlEncodedFormEntity object to contain the request parameters and set them as entities for the POST request. The entity is obtained in the response, and then the entity is converted into a string and output.
- Send files
When you need to send files, you should use the MultipartEntityBuilder object. Here is an example of an included file:
CloseableHttpClient httpClient = HttpClients.createDefault(); HttpPost httpPost = new HttpPost("http://localhost:8080/upload"); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.addBinaryBody("file", new File("example.txt")); httpPost.setEntity(builder.build()); try (CloseableHttpResponse response = httpClient.execute(httpPost)) { HttpEntity entity = response.getEntity(); if (entity != null) { String result = EntityUtils.toString(entity, "UTF-8"); System.out.println(result); } } catch (IOException e) { e.printStackTrace(); }
The above code will transfer a file named example.txt to localhost:8080. In this example, we use a MultipartEntityBuilder object and add the file as binary content. The entity is obtained in the response, and then the entity is converted into a string and output.
- Add header information when sending a request
Sometimes, we need to add header information to the request. The following is an example of adding header information:
CloseableHttpClient httpClient = HttpClients.createDefault(); HttpPost httpPost = new HttpPost("https://www.baidu.com"); httpPost.setHeader("User-Agent", "Mozilla/5.0"); try (CloseableHttpResponse response = httpClient.execute(httpPost)) { HttpEntity entity = response.getEntity(); if (entity != null) { String result = EntityUtils.toString(entity, "UTF-8"); System.out.println(result); } } catch (IOException e) { e.printStackTrace(); }
The above code will send a GET request to Baidu and add a User-Agent header information. In this example, we use the HttpPost object to create a GET request and call the setHeader method to add header information. The entity is obtained in the response, and then the entity is converted into a string and output.
- Set the timeout when sending a request
When sending a request, you can also set the request timeout and response timeout. This prevents the client from blocking indefinitely while waiting for a response from the server. The following is an example of setting the timeout:
CloseableHttpClient httpClient = HttpClients.createDefault(); HttpPost httpPost = new HttpPost("https://www.baidu.com"); RequestConfig requestConfig = RequestConfig.custom() .setConnectTimeout(5000) // 连接超时时间 .setSocketTimeout(5000) // 响应超时时间 .build(); httpPost.setConfig(requestConfig); try (CloseableHttpResponse response = httpClient.execute(httpPost)) { HttpEntity entity = response.getEntity(); if (entity != null) { String result = EntityUtils.toString(entity, "UTF-8"); System.out.println(result); } } catch (IOException e) { e.printStackTrace(); }
The above code will send a POST request to Baidu and set the connection timeout and response timeout to 5 seconds. In this example, we use the RequestConfig object and set the connection timeout and response timeout through the custom method. The entity is obtained in the response, and then the entity is converted into a string and output.
- Summary
The Apache HttpClient library provides many convenient APIs that allow Java developers to perform HTTP requests very easily. This article describes how to use Apache HttpClient to send GET requests, POST requests, requests that include files, requests that add header information, and requests that set timeouts. I hope this article can provide some help to Java developers using Apache HttpClient.
The above is the detailed content of Using Apache HttpClient for HTTP requests in Java API development. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



From start to finish: How to use php extension cURL for HTTP requests Introduction: In web development, it is often necessary to communicate with third-party APIs or other remote servers. Using cURL to make HTTP requests is a common and powerful way. This article will introduce how to use PHP to extend cURL to perform HTTP requests, and provide some practical code examples. 1. Preparation First, make sure that php has the cURL extension installed. You can execute php-m|grepcurl on the command line to check

How to solve the problem of HTTP request connection being refused in Java development. In Java development, we often encounter the problem of HTTP request connection being refused. This problem may occur because the server side restricts access rights, or the network firewall blocks access to HTTP requests. Fixing this problem requires some adjustments to your code and environment. This article will introduce several common solutions. Check the network connection and server status. First, confirm that your network connection is normal. You can try to access other websites or services to see

Brief introduction to the reason for the http request error: 504GatewayTimeout: During network communication, the client interacts with the server by sending HTTP requests. However, sometimes we may encounter some error messages during the process of sending the request. One of them is the 504GatewayTimeout error. This article will explore the causes and solutions to this error. What is the 504GatewayTimeout error? GatewayTimeo

http request error: Solution to SocketError When making network requests, we often encounter various errors. One of the common problems is SocketError. This error is thrown when our application cannot establish a connection with the server. In this article, we will discuss some common causes and solutions of SocketError. First, we need to understand what Socket is. Socket is a communication protocol that allows applications to

To set query parameters for HTTP requests in Go, you can use the http.Request.URL.Query().Set() method, which accepts query parameter names and values as parameters. Specific steps include: Create a new HTTP request. Use the Query().Set() method to set query parameters. Encode the request. Execute the request. Get the value of a query parameter (optional). Remove query parameters (optional).

Free api interface website: 1. UomgAPI: a platform that provides stable and fast free API services, with over 100 API interfaces; 2. free-api: provides multiple free API interfaces; 3. JSON API: provides free data API interface; 4. AutoNavi Open Platform: Provides map-related API interfaces; 5. Face recognition Face++: Provides face recognition-related API interfaces; 6. Speed data: Provides over a hundred free API interfaces, suitable for various needs In the case of data sources; 7. Aggregate data, etc.

How Nginx implements HTTP request retry configuration requires specific code examples. Nginx is a very popular open source reverse proxy server. It has powerful functions and flexible configuration options and can be used to implement HTTP request retry configuration. In network communication, sometimes the HTTP request we initiate may fail due to various reasons, such as network delay, server load, etc. In order to improve the reliability and stability of the application, we may need to retry when the request fails. The following will introduce how to use Ng

How to use Nginx to compress and decompress HTTP requests Nginx is a high-performance web server and reverse proxy server that is powerful and flexible. When processing HTTP requests, you can use the gzip and gunzip modules provided by Nginx to compress and decompress the requests to reduce the amount of data transmission and improve the request response speed. This article will introduce the specific steps of how to use Nginx to compress and decompress HTTP requests, and provide corresponding code examples. Configure gzip module
