为什么我得到“方法 uri(URI) 未定义对象类型”?

问题描述 投票:0回答:0

我正在编写一个简单的代码来调用 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());
    }
}
java api http httprequest httpresponse
© www.soinside.com 2019 - 2024. All rights reserved.