maven 如何从HttpResponse示例中获取Entity对象的内容?

uqdfh47h  于 2024-01-06  发布在  Maven
关注(0)|答案(1)|浏览(146)

每次我试图获取Entity对象的内容时都会得到一个错误。

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());
    }
}

字符串
我试着改变版本库的版本,并在官方文档中寻找可以帮助我解决这个问题的信息。

<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>

f8rj6qna

f8rj6qna1#

getEntity()方法属于CloseableHttpResponse,而不是HttpResponse。只需更改代码以使用前者:

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

字符串
请注意,CloseableHttpClient#execute(ClassicHttpRequest)已被弃用。您应该使用带有HttpClientResponseHandler的execute,这将自动释放任何资源。下面是一个示例:

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);
    }
});

相关问题