Search code examples
javamavenhttpclient

How do I get the content of the Entity object from the HttpResponse instance?


I get an error everytime I try to get the content of an Entity object.

package com.mycompany.prueba_rest;

import java.io.IOException;
import java.util.Scanner;
import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.core5.http.HttpResponse;

public class Prueba_REST {

    public static void main(String[] args) throws IOException {
    
       // Crear objeto HttpClient.
       CloseableHttpClient httpclient = HttpClients.createDefault();

       //Crear un objeto HttpGet.
       HttpGet httpget = new HttpGet("https://www.tutorialspoint.com");

       //Imprimir por pantalla el método usado.
       System.out.println("Request Type: "+httpget.getMethod());

       //Ejecutar el pedido GET.
       HttpResponse httpresponse = httpclient.execute(httpget);

                                                  // Error here!
       Scanner scanner = new Scanner(httpresponse.getEntity().getContent());
    }
}

I tried changing the version of the repository and looking for information in the official documentation that could help me solve this problem.

<dependencies>
    <!-- https://mvnrepository.com/artifact/org.apache.httpcomponents.client5/httpclient5 -->
    <dependency>
        <groupId>org.apache.httpcomponents.client5</groupId>
        <artifactId>httpclient5</artifactId>
        <version>5.2.1</version>
    </dependency>
</dependencies>

Solution

  • The getEntity() method belongs to CloseableHttpResponse, not HttpResponse. Just change your code to use the former:

    CloseableHttpResponse httpresponse = httpclient.execute(httpget);
    Scanner scanner = new Scanner(httpresponse.getEntity().getContent());
    

    Be aware that CloseableHttpClient#execute(ClassicHttpRequest) is deprecated. You should instead use an execute with an HttpClientResponseHandler, which will automatically deallocate any resources. Here's an example:

    MyObject myObject = httpclient.execute(httpget, new HttpClientResponseHandler<MyObject>() {
        @Override
        public MyObject handleResponse(ClassicHttpResponse response) throws HttpException, IOException {
            Scanner scanner = new Scanner(response.getEntity().getContent());
            int id = scanner.nextInt();
            String name = scanner.next();
            String description = scanner.nextLine();
            return new MyObject(id, name, description);
        }
    });