我正在编写一个简单的代码来调用 Java 中的 API,下面是我的代码。我遇到以下错误,并且没有从互联网上获得任何解决方案。任何人都可以在这里帮忙。 如果我需要在我的环境中导入任何包或 jar,请告诉我。
我得到的错误是
The method uri(URI) is undefined for the type Object
The method ofString() is undefined for the type String
我的代码如下:
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
public class callAPI {
public static void main(String[] args) throws URISyntaxException, IOException, InterruptedException {
HttpRequest request = HttpRequest.newBuilder()`
.uri(URI.create("https://jokes-by-api-ninjas.p.rapidapi.com/v1/jokes"))
.headers("X-RapidAPI-Host", "jokes-by-api-ninjas.p.rapidapi.com","X-RapidAPI-Key", "your-rapidapi-key")
.GET()
.build();
HttpResponse response = null;
HttpClient client = new HttpClient();
try {
response = client.send(request, HttpResponse.BodyHandlers.ofString());
}
catch (IOException | InterruptedException e) {
e.printStackTrace();`
}
System.out.println(response.body());
}
}