每次try 获取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());
    }
}

我try 更改存储库的版本,并在官方文档中查找可以帮助我解决此问题的信息.

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

推荐答案

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

Java相关问答推荐

当列顺序更改时,Table View列列表的Change. wasPermanted()总是返回假

JPackage-results已安装-如何添加系统属性?

Listview—在Android Java中正确链接项目时出错

为什么BasicComboBoxRenderer在文本不存在或文本为空的情况下设置两次文本?

是否保证在事务性块的末尾标记违反约束?

Exe4j创建的应用程序无法再固定在任务栏Windows 11上

对于几乎不涉及逻辑的请求,您是否应该使用命令模式?

Java:使用Class.cast()将对象转换为原始数组

如何让DTO接受空字符串字段,但如果它们不为空,则应用JPA验证?

在Spring Boot中使用哪个Java类来存储创建时间戳?

与Spring Boot相关的实体未正确保存

在Eclipse中数组的可空性

try 在Android Studio中的infoWindow中使用EditText(Java)

当构造函数创建一个新实例时,Java为什么需要&new";

如何配置空手道以使用FeignClient或RestTemplate代替ApacheHttpClient

当我在Java中有一个Synchronized块来递增int时,必须声明一个变量Volatile吗?

如何使用Rascal Evaluator从编译的JAR访问Rascal函数?

javax.crypto-密码对象-提供者服务是如何工作的?

Spring Boot Security-每个端点都被403禁止,Spring记录一个BasicErrorController#错误(HttpServlet请求)

如何在 Android Studio 中删除 ImageView 和屏幕/父级边缘之间的额外空间?