import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.utils.URIBuilder; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.HttpResponse; import java.net.URI; public class HttpGetExample { public static void main(String[] args) throws Exception { HttpClient httpClient = HttpClientBuilder.create().build(); URIBuilder uriBuilder = new URIBuilder("http://example.com"); URI uri = uriBuilder.build(); HttpGet httpGet = new HttpGet(uri); HttpResponse response = httpClient.execute(httpGet); System.out.println(response.getStatusLine().getStatusCode()); System.out.println(response.getEntity().getContent().toString()); } }
import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.HttpResponse; public class HttpPostJsonExample { public static void main(String[] args) throws Exception { HttpClient httpClient = HttpClientBuilder.create().build(); HttpPost httpPost = new HttpPost("http://example.com/api"); httpPost.setHeader("Content-Type", "application/json"); String jsonPayload = "{\"name\": \"John Doe\", \"age\": 30}"; StringEntity entity = new StringEntity(jsonPayload); httpPost.setEntity(entity); HttpResponse response = httpClient.execute(httpPost); System.out.println(response.getStatusLine().getStatusCode()); System.out.println(response.getEntity().getContent().toString()); } }This example sends a POST request to `http://example.com/api` with a JSON payload and prints the response status code and content. Package library: `org.apache.http.client` is part of the Apache HttpComponents library.