每次我试图获取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>
型
1条答案
按热度按时间f8rj6qna1#
getEntity()
方法属于CloseableHttpResponse
,而不是HttpResponse
。只需更改代码以使用前者:字符串
请注意,
CloseableHttpClient#execute(ClassicHttpRequest)
已被弃用。您应该使用带有HttpClientResponseHandler
的execute,这将自动释放任何资源。下面是一个示例:型