To send HTTP requests and process responses using the Apache HttpClient library in Java, follow these steps:
- Add the HttpClient Dependency
If you're using Maven, include the following dependency in your pom.xml:
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.13</version>
</dependency>
- Instantiate the HTTP Client
Use HttpClientBuilder to create a reusable client instance:
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
CloseableHttpClient client = HttpClientBuilder.create().build();
- Construct the HTTP Request
Create an appropriate request object based on the desired method:
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
HttpGet getReq = new HttpGet("https://api.example.com/data");
HttpPost postReq = new HttpPost("https://api.example.com/submit");
- Configure Request Details
Set headers or body content as needed:
import org.apache.http.entity.StringEntity;
postReq.setHeader("Content-Type", "application/json");
String jsonPayload = "{\"name\": \"test\"}";
postReq.setEntity(new StringEntity(jsonPayload, "UTF-8"));
- Execute the Request and Capture the Response
Use the client to execute the request and handle the response:
import org.apache.http.client.ResponseHandler;
import org.apache.http.impl.client.BasicResponseHandler;
ResponseHandler<String> handler = new BasicResponseHandler();
String responseBody = client.execute(postReq, handler);
- Processs the Response
The response body is now available as a string for further processing.
Complete Example
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import java.io.IOException;
public class HttpClientExample {
public static void main(String[] args) throws IOException {
try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
HttpPost postRequest = new HttpPost("http://localhost:8082/unit/queryunitbybase");
postRequest.setHeader("Content-Type", "application/json");
String payload = "{\"chineseName\":\"横须贺港\"}";
postRequest.setEntity(new StringEntity(payload, "UTF-8"));
BasicResponseHandler responseHandler = new BasicResponseHandler();
String response = httpClient.execute(postRequest, responseHandler);
System.out.println("Response: " + response);
}
}
}