有没有办法将内容从API打印到本地主机服务器



我试图学习spring,同时构建一个小项目,但遇到了一个问题。一切都正常工作,但我不知道如何使用打印在Eclipse控制台中的API方法内容。

在我的控制器中,我拥有使用API特定方法所需的所有信息。我使用"@GetMapping("/季节"(并且我使用来自在线API的代码片段(带密钥(。在VIEW文件夹中(基本上是保存JSP文件的地方,例如:seasons.JSP(,我试图从API的响应中检索数据。

这是API的响应:;CCD_ 1";

更新:

以下是一些参考代码:

@GetMapping("/seasons")
public String seasons(Model theModel) throws IOException, InterruptedException {
List<Integer> SeasonsList = new ArrayList<>();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://api-formula-1.p.rapidapi.com/seasons"))
.header("x-rapidapi-host", "api-formula-1.p.rapidapi.com")
.header("x-rapidapi-key", "5a6f44fa10msh40be2be8d20bc5bp18a190jsnb4478dcbc8f1")
.method("GET", HttpRequest.BodyPublishers.noBody())
.build();
HttpResponse<String> response = HttpClient.newHttpClient().send(request, HttpResponse.BodyHandlers.ofString());

JSONObject seasonsObject = new JSONObject(response.body());
for(int i = 0; i < seasonsObject.length(); i++) {
JSONArray object = seasonsObject.getJSONArray("response");
for(int j = 0 ; i < object.length(); j++) {
SeasonsList.add(object.getInt(j));

}
System.out.println(object);
}

theModel.addAttribute("theSeasons", SeasonsList);
return "seasons";
}

HTML文件:

<html xmlns:th ="http://www.thymeleaf.org">
<head>

<title>The Formula 1 Seasons are</title>

</head>
<body>
<p th:text ="'The seasons are:  ' + ${theSeasons}"/>
</body>

</html>

我想要的是展示";季节为:2012年、2013年、2014年等。

我在控制台中得到一个错误:";org.json.JSONException:找不到JSONArray[10]">

如果你需要我的项目的任何细节,请告诉我。

您的内部循环使用了错误的循环变量,并将j移动到数组末尾:

// Don't do this
for (int j = 0 ; i < object.length(); j++) { // Comparing "i"; compare "j" instead
// Do this
for (int j = 0 ; j < object.length(); j++) {

不过,目前还不清楚为什么需要一个外部循环;你正在从一个已知的响应中提取一个已知属性;外环AFAICT没有任何原因。

最新更新