apache httpclient http get request

www.‮editfigi‬a.com

To make an HTTP GET request using Apache HttpClient, follow these steps:

  1. Create an instance of HttpClient:
HttpClient httpClient = HttpClientBuilder.create().build();
  1. Create an instance of HttpGet with the URL to be fetched:
HttpGet httpGet = new HttpGet("http://www.example.com");
  1. Execute the request and get the response:
HttpResponse httpResponse = httpClient.execute(httpGet);
  1. Extract the response body as a String:
String responseBody = EntityUtils.toString(httpResponse.getEntity());
  1. 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.