如何通过 REST API 和 Spring MVC 提取电视节目详细信息?
REpresentational State Transfer (REST)是一种架构风格,它定义了一组用于创建 Web 服务的约束。 REST API 是一种无需任何处理即可以简单灵活的方式访问 Web 服务的方式。 Spring MVC 是一个用于构建 Web 应用程序的 Web MVC 框架。它是一个与 spring boot、spring-security 等相同的 spring 模块。术语 MVC 代表 Model-View-Controller 架构。 REST API 调用现在广泛用于获取各种信息,例如天气、邮政编码、加密货币、大学详细信息等,在本文中,让我们尝试通过以下方式获取电视连续剧详细信息
http://api.tvmaze.com/search/shows?q=
例子:
https://api.tvmaze.com/search/shows?q=mahabharata
JSON输出:
[
{
"score": 0.6494496,
"show": {
"id": 60856,
"url": "https://www.tvmaze.com/shows/60856/the-mahabharata",
"name": "The Mahabharata",
"type": "Scripted",
"language": "English",
"genres": [],
"status": "Ended",
"runtime": null,
"averageRuntime": null,
"premiered": "1990-03-10",
"ended": "1990-03-24",
"officialSite": null,
"schedule": {
"time": "",
"days": []
},
"rating": {
"average": null
},
"weight": 0,
"network": {
"id": 269,
"name": "Star Plus",
"country": {
"name": "India",
"code": "IN",
"timezone": "Asia/Kolkata"
},
"officialSite": null
},
"webChannel": null,
"dvdCountry": null,
"externals": {
"tvrage": null,
"thetvdb": 213551,
"imdb": "tt0097810"
},
"image": {
"medium": "https://static.tvmaze.com/uploads/images/medium_portrait/398/996547.jpg",
"original": "https://static.tvmaze.com/uploads/images/original_untouched/398/996547.jpg"
},
"summary": null,
"updated": 1646508699,
"_links": {
"self": {
"href": "https://api.tvmaze.com/shows/60856"
},
"previousepisode": {
"href": "https://api.tvmaze.com/episodes/2289706"
}
}
}
},
{
"score": 0.5061876,
"show": {
"id": 5016,
"url": "https://www.tvmaze.com/shows/5016/mahabharat",
"name": "Mahabharat",
"type": "Scripted",
"language": "Hindi",
"genres": [
"Drama",
"History"
],
"status": "Ended",
"runtime": 20,
"averageRuntime": 20,
"premiered": "2013-09-16",
"ended": "2014-08-16",
"officialSite": "http://www.hotstar.com/#!/mahabharat-435-s",
"schedule": {
"time": "20:30",
"days": [
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday",
"Sunday"
]
},
"rating": {
"average": null
},
"weight": 47,
"network": {
"id": 269,
"name": "Star Plus",
"country": {
"name": "India",
"code": "IN",
"timezone": "Asia/Kolkata"
}
},
"webChannel": null,
"dvdCountry": null,
"externals": {
"tvrage": 46350,
"thetvdb": 273350,
"imdb": "tt3212600"
},
"image": {
"medium": "https://static.tvmaze.com/uploads/images/medium_portrait/21/54241.jpg",
"original": "https://static.tvmaze.com/uploads/images/original_untouched/21/54241.jpg"
},
"summary": "The story of the throne of Hastinapura, the kingdom ruled by the Kuru clan. The two collateral branches of the family that participate in the struggle of the throne of Hastinapura are the Kaurava and the Pandava. Although the Kaurava is the senior branch of the family, Duryodhana, the eldest Kaurava, is younger than Yudhisthira, the eldest Pandava. Both Duryodhana and Yudhisthira claim to be first in line to inherit the throne. The struggle culminates in the great battle of Kurukshetra, in which the Pandavas are ultimately victorious. The battle produces complex conflicts of kinship and friendship, instances of family loyalty and duty taking precedence over what is right, as well as the converse.
",
"updated": 1604823863,
"_links": {
"self": {
"href": "https://api.tvmaze.com/shows/5016"
},
"previousepisode": {
"href": "https://api.tvmaze.com/episodes/314287"
}
}
}
},
{
"score": 0.42338097,
"show": {
"id": 16607,
"url": "https://www.tvmaze.com/shows/16607/mahabharat",
"name": "Mahabharat",
"type": "Scripted",
"language": "Hindi",
"genres": [
"Drama"
],
"status": "Ended",
"runtime": 45,
"averageRuntime": 45,
"premiered": "1988-10-02",
"ended": "1990-07-15",
"officialSite": null,
"schedule": {
"time": "",
"days": [
"Sunday"
]
},
"rating": {
"average": null
},
"weight": 17,
"network": {
"id": 1093,
"name": "DD National",
"country": {
"name": "India",
"code": "IN",
"timezone": "Asia/Kolkata"
}
},
"webChannel": null,
"dvdCountry": null,
"externals": {
"tvrage": null,
"thetvdb": 84349,
"imdb": "tt0158417"
},
"image": {
"medium": "https://static.tvmaze.com/uploads/images/medium_portrait/55/138442.jpg",
"original": "https://static.tvmaze.com/uploads/images/original_untouched/55/138442.jpg"
},
"summary": "Mahabharat is a successful Indian television series based on the ancient Indian epic Mahabharata. The 94-episode series originally ran from 1988 to 1990. It was produced by B. R. Chopra and directed by his son, Ravi Chopra.
",
"updated": 1573325769,
"_links": {
"self": {
"href": "https://api.tvmaze.com/shows/16607"
},
"previousepisode": {
"href": "https://api.tvmaze.com/episodes/762035"
}
}
}
}
]
使用 Spring Framework,让我们尝试提取 REST API 并将其呈现在页面上。
分步实施
项目结构:
pom.xml:
XML
4.0.0
com.TVShow.TVShow_Rest_API
TVShow_Rest_API
war
0.0.1-SNAPSHOT
TVShow
http://maven.apache.org
false
5.1.0.RELEASE
org.springframework
spring-webmvc
${spring-version}
org.springframework
spring-test
${spring-version}
javax.servlet.jsp.jstl
javax.servlet.jsp.jstl-api
1.2.1
taglibs
standard
1.1.2
javax.servlet
javax.servlet-api
3.1.0
provided
javax.servlet.jsp
javax.servlet.jsp-api
2.3.1
provided
com.google.code.gson
gson
2.8.6
commons-io
commons-io
2.5
junit
junit
4.12
test
TVShow
src/main/java
maven-compiler-plugin
3.5.1
1.8
org.apache.maven.plugins
maven-war-plugin
3.3.2
org.codehaus.mojo
tomcat-maven-plugin
1.0-beta-1
Java
TVShow
// for making the page styles are applied
// We need to input the search string in this box
Java
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = { "com.TVShow.TVShow_Rest_API" })
public class AppConfig {
@Bean
public InternalResourceViewResolver resolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setViewClass(JstlView.class);
resolver.setPrefix("/");
resolver.setSuffix(".jsp");
return resolver;
}
}
Java
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
public class SpringMvcDispatcherServletInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Class>[] getRootConfigClasses() {
return null;
}
@Override
protected Class>[] getServletConfigClasses() {
return new Class[] { AppConfig.class };
}
@Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
}
Java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.StringTokenizer;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
@Controller
public class TVShowController {
@RequestMapping("/getTVShowDetailsBySearchString")
public @ResponseBody
JsonObject getTVShowDetailsBySearchString(String searchStr) throws IOException {
// According to the search string, JSONArray
// or JSON Object is constructed.
// In our case, it is producing JSONArray
JsonArray jsonArray = new JsonArray();
jsonArray = getTVShowDetailsBySearchStr(searchStr);
JsonObject finalJsonObject = new JsonObject();
ArrayList scoreList = new ArrayList();
ArrayList showUrlList = new ArrayList();
ArrayList showUrlLinks = new ArrayList();
ArrayList telecastedList = new ArrayList();
ArrayList imdbList = new ArrayList();
Iterator objectIterator = jsonArray.iterator();
// Iterating
while(objectIterator.hasNext()) {
JsonElement object = objectIterator.next();
JsonObject jObj = object.getAsJsonObject();
// We have to get the score and
// replace the special characters
scoreList.add(jObj.get("score").toString().replaceAll("^\"|\"$", ""));
// Similarly show
showUrlList.add(jObj.get("show").toString().replaceAll("^\"|\"$", ""));
}
for (int i = 0;i < showUrlList.size();i++) {
StringTokenizer jsonTokenizer = new StringTokenizer(showUrlList.get(i).toString(),",");
String expectedTag = null;
int idx = 0;
while (jsonTokenizer.hasMoreTokens()) {
expectedTag = jsonTokenizer.nextToken();
if (expectedTag.contains("url")) {
showUrlLinks.add(expectedTag.substring(7,expectedTag.length()-1).toString());
}
if (expectedTag.contains("timezone")) {
telecastedList.add(expectedTag.substring(12,expectedTag.length()-3).toString());
}
if (expectedTag.contains("imdb")) {
imdbList.add(expectedTag.substring(8,expectedTag.length()-2).toString());
}
}
}
finalJsonObject.addProperty("scores", scoreList.toString());
finalJsonObject.addProperty("scoresize", scoreList.size());
finalJsonObject.addProperty("url", showUrlLinks.toString());
finalJsonObject.addProperty("urlsize", showUrlLinks.size());
finalJsonObject.addProperty("timezone", telecastedList.toString());
finalJsonObject.addProperty("imdb", imdbList.toString());
finalJsonObject.addProperty("imdbsize", imdbList.size());
// After retrieving the elements,
// in an object , all are constructed
return finalJsonObject;
}
private JsonArray getTVShowDetailsBySearchStr(String searchString) throws IOException {
StringBuilder responseData = new StringBuilder();
JsonArray jsonArray = null;
URL url = null;
// http://api.tvmaze.com/search/shows?q=
// is the url to access the TV show details
url = new URL("http://api.tvmaze.com/search/shows?q=" + searchString);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("User-Agent", "Mozilla/5.0");
int responseCode = con.getResponseCode();
System.out.println("\nSending 'GET' request to URL : " + url);
// System.out.println("Response Code : " + responseCode);
try (BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()))) {
String line;
while ((line = in.readLine()) != null) {
responseData.append(line);
}
// It is getting converted to
// JSONArray by means of below code
jsonArray = new Gson().fromJson(responseData.toString(), JsonArray.class);
}
return jsonArray;
}
}
index.jsp:
这是项目部署在 tomcat 中时呈现的页面
Java
TVShow
// for making the page styles are applied
// We need to input the search string in this box
输出:
在输入框中输入任何电视节目名称后,我们将获得以下详细信息。
执行过程:
在 JSP 页面中,使用搜索字符串调用“GET”方法,并将其重定向到 Spring Controller 类,其中 REST API URL http://api.tvmaze.com/search/shows?q=
"score", "url" and "imdb" values alone
Example:
"score": 0.42338097,
"url": "https://www.tvmaze.com/shows/16607/mahabharat",
"imdb": "tt0158417"
实际上,在这个页面上,我们只检索了 TVShowScore、TVShow URL 和 IMDB。但是我们可以获得 JSON 中可用的所有其他详细信息。检索数据和解析 JSON 输出所需的代码如下。实现流程的重要必要文件
应用配置。Java:
Java
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = { "com.TVShow.TVShow_Rest_API" })
public class AppConfig {
@Bean
public InternalResourceViewResolver resolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setViewClass(JstlView.class);
resolver.setPrefix("/");
resolver.setSuffix(".jsp");
return resolver;
}
}
SpringMvcDispatcherServletInitializer。Java:
Java
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
public class SpringMvcDispatcherServletInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Class>[] getRootConfigClasses() {
return null;
}
@Override
protected Class>[] getServletConfigClasses() {
return new Class[] { AppConfig.class };
}
@Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
}
电视节目控制器。Java:
Java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.StringTokenizer;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
@Controller
public class TVShowController {
@RequestMapping("/getTVShowDetailsBySearchString")
public @ResponseBody
JsonObject getTVShowDetailsBySearchString(String searchStr) throws IOException {
// According to the search string, JSONArray
// or JSON Object is constructed.
// In our case, it is producing JSONArray
JsonArray jsonArray = new JsonArray();
jsonArray = getTVShowDetailsBySearchStr(searchStr);
JsonObject finalJsonObject = new JsonObject();
ArrayList scoreList = new ArrayList();
ArrayList showUrlList = new ArrayList();
ArrayList showUrlLinks = new ArrayList();
ArrayList telecastedList = new ArrayList();
ArrayList imdbList = new ArrayList();
Iterator objectIterator = jsonArray.iterator();
// Iterating
while(objectIterator.hasNext()) {
JsonElement object = objectIterator.next();
JsonObject jObj = object.getAsJsonObject();
// We have to get the score and
// replace the special characters
scoreList.add(jObj.get("score").toString().replaceAll("^\"|\"$", ""));
// Similarly show
showUrlList.add(jObj.get("show").toString().replaceAll("^\"|\"$", ""));
}
for (int i = 0;i < showUrlList.size();i++) {
StringTokenizer jsonTokenizer = new StringTokenizer(showUrlList.get(i).toString(),",");
String expectedTag = null;
int idx = 0;
while (jsonTokenizer.hasMoreTokens()) {
expectedTag = jsonTokenizer.nextToken();
if (expectedTag.contains("url")) {
showUrlLinks.add(expectedTag.substring(7,expectedTag.length()-1).toString());
}
if (expectedTag.contains("timezone")) {
telecastedList.add(expectedTag.substring(12,expectedTag.length()-3).toString());
}
if (expectedTag.contains("imdb")) {
imdbList.add(expectedTag.substring(8,expectedTag.length()-2).toString());
}
}
}
finalJsonObject.addProperty("scores", scoreList.toString());
finalJsonObject.addProperty("scoresize", scoreList.size());
finalJsonObject.addProperty("url", showUrlLinks.toString());
finalJsonObject.addProperty("urlsize", showUrlLinks.size());
finalJsonObject.addProperty("timezone", telecastedList.toString());
finalJsonObject.addProperty("imdb", imdbList.toString());
finalJsonObject.addProperty("imdbsize", imdbList.size());
// After retrieving the elements,
// in an object , all are constructed
return finalJsonObject;
}
private JsonArray getTVShowDetailsBySearchStr(String searchString) throws IOException {
StringBuilder responseData = new StringBuilder();
JsonArray jsonArray = null;
URL url = null;
// http://api.tvmaze.com/search/shows?q=
// is the url to access the TV show details
url = new URL("http://api.tvmaze.com/search/shows?q=" + searchString);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("User-Agent", "Mozilla/5.0");
int responseCode = con.getResponseCode();
System.out.println("\nSending 'GET' request to URL : " + url);
// System.out.println("Response Code : " + responseCode);
try (BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()))) {
String line;
while ((line = in.readLine()) != null) {
responseData.append(line);
}
// It is getting converted to
// JSONArray by means of below code
jsonArray = new Gson().fromJson(responseData.toString(), JsonArray.class);
}
return jsonArray;
}
}
结论
通过使用 Spring-webmvc,我们可以从 REST API 调用中获取详细信息。上面就是一个很好的例子。同样,有很多可用的开源 REST API 调用。这意味着我们可以使用它们来检索数据。开源 REST API 调用的几个示例。 API Name Description Sample URLCoinBase Currency codes and Names https://api.coinbase.com/v2/currencies ExchangeRate-API Exchange Rates https://open.er-api.com/v6/latest/USD WeatherDB Weather Data https://weatherdbi.herokuapp.com/data/weather/london