这些是我使用的导入:
import org.apache.hc.client5.http.classic.HttpClient;
import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.core5.http.HttpEntity;
import org.apache.hc.core5.http.HttpResponse;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.http.io.entity.StringEntity;
import org.apache.hc.core5.net.URIBuilder;
import java.net.URI;
Run Code Online (Sandbox Code Playgroud)
这是我制作的代码:
HttpResponse response = httpclient.execute(request);
HttpEntity entity = response.getEntity();
Run Code Online (Sandbox Code Playgroud)
但我收到这个错误:
Cannot resolve method 'getEntity' in 'HttpResponse'
Run Code Online (Sandbox Code Playgroud)
我尝试寻找解决方案,但它们都是针对 Android 的。我正在使用 Java,并且我使用 IntelliJ
此代码来自此示例:
// // This sample uses the Apache HTTP client from HTTP Components (http://hc.apache.org /httpcomponents-client-ga/)
public class JavaSample
{
public static void main(String[] args)
{
HttpClient httpclient = HttpClients.createDefault();
try
{
URIBuilder builder = new URIBuilder("https://gateway.apiportal.ns.nl/reisinformatie-api/api/v2/departures");
builder.setParameter("station", "{string}");
builder.setParameter("uicCode", "{string}");
builder.setParameter("dateTime", "{integer}");
builder.setParameter("lang", "nl");
builder.setParameter("maxJourneys", "{integer}");
URI uri = builder.build();
HttpGet request = new HttpGet(uri);
request.setHeader("Ocp-Apim-Subscription-Key", "{subscription key}");
// Request body
StringEntity reqEntity = new StringEntity("{body}");
request.setEntity(reqEntity);
HttpResponse response = httpclient.execute(request);
HttpEntity entity = response.getEntity();
if (entity != null)
{
System.out.println(EntityUtils.toString(entity));
}
}
catch (Exception e)
{
System.out.println(e.getMessage());
}
}
}
Run Code Online (Sandbox Code Playgroud)
我究竟做错了什么?
这解决了这个问题:
ClassicHttpResponse response = (ClassicHttpResponse) httpclient.execute(request);
HttpEntity entity = response.getEntity();
Run Code Online (Sandbox Code Playgroud)