apache httpclient http get request
www.editfigia.com
To make an HTTP GET request using Apache HttpClient, follow these steps:
- Create an instance of HttpClient:
HttpClient httpClient = HttpClientBuilder.create().build();
- Create an instance of HttpGet with the URL to be fetched:
HttpGet httpGet = new HttpGet("http://www.example.com");
- Execute the request and get the response:
HttpResponse httpResponse = httpClient.execute(httpGet);
- Extract the response body as a String:
String responseBody = EntityUtils.toString(httpResponse.getEntity());
- Release the connection:
EntityUtils.consume(httpResponse.getEntity());
Here's an example that puts it all together:
import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.HttpResponse; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.util.EntityUtils; public class HttpClientExample { public static void main(String[] args) throws Exception { HttpClient httpClient = HttpClientBuilder.create().build(); HttpGet httpGet = new HttpGet("http://www.example.com"); HttpResponse httpResponse = httpClient.execute(httpGet); String responseBody = EntityUtils.toString(httpResponse.getEntity()); System.out.println(responseBody); EntityUtils.consume(httpResponse.getEntity()); } }
This example creates an HttpClient instance, creates an HttpGet request for the URL "http://www.example.com", executes the request using the HttpClient's execute() method, extracts the response body as a String, prints it to the console, and releases the connection. Note that you'll need to handle any exceptions that might be thrown by these methods.