成人免费xxxxx在线视频软件_久久精品久久久_亚洲国产精品久久久_天天色天天色_亚洲人成一区_欧美一级欧美三级在线观看

如何通過 REST API 和 Spring MVC 提取電視節目詳細信息?

開發
REST API 是一種無需任何處理即可簡單靈活地訪問 Web 服務的方式。Spring MVC是一個用于構建 Web 應用程序的 Web MVC 框架。它是一個與 spring boot、spring-security 等相同的 spring 模塊。

表述性狀態傳輸 (REST)是一種架構風格,它定義了一組用于創建 Web 服務的約束。REST API 是一種無需任何處理即可簡單靈活地訪問 Web 服務的方式。

Spring MVC是一個用于構建 Web 應用程序的 Web MVC 框架。它是一個與 spring boot、spring-security 等相同的 spring 模塊。術語 MVC 代表模型-視圖-控制器架構。REST API 調用如今被廣泛用于獲取各種信息,例如天氣、郵政編碼、secret、大學詳細信息等.

在本文中,讓我們嘗試通過以下方式獲取電視連續劇詳細信息。

http://api.tvmaze.com/search/shows?q=<任何電視連續劇名稱>

例子:

https://api.tvmaze.com/search/shows?q=mahabharata

JSON 輸出:

[
    {
        "score": 0.54483813,
        "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": 5,
            "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.40868765,
        "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": 37,
            "network": {
                "id": 269,
                "name": "Star Plus",
                "country": {
                    "name": "India",
                    "code": "IN",
                    "timezone": "Asia/Kolkata"
                },
                "officialSite": null
            },
            "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": "<p>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.</p>",
            "updated": 1604823863,
            "_links": {
                "self": {
                    "href": "https://api.tvmaze.com/shows/5016"
                },
                "previousepisode": {
                    "href": "https://api.tvmaze.com/episodes/314287"
                }
            }
        }
    },
    {
        "score": 0.38368216,
        "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": 24,
            "network": {
                "id": 1093,
                "name": "DD National",
                "country": {
                    "name": "India",
                    "code": "IN",
                    "timezone": "Asia/Kolkata"
                },
                "officialSite": null
            },
            "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": "<p><b>Mahabharat</b> 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.</p>",
            "updated": 1573325769,
            "_links": {
                "self": {
                    "href": "https://api.tvmaze.com/shows/16607"
                },
                "previousepisode": {
                    "href": "https://api.tvmaze.com/episodes/762035"
                }
            }
        }
    }
]

使用Spring框架,讓我們嘗試提取REST API并將其呈現在頁面上。

項目結構:

pom.xml 編寫:

<project xmlns="http://maven.apache.org/POM/4.0.0"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
						http://maven.apache.org/maven-v4_0_0.xsd"> 
	<modelVersion>4.0.0</modelVersion> 
	<groupId>com.TVShow.TVShow_Rest_API</groupId> 
	<artifactId>TVShow_Rest_API</artifactId> 
	<packaging>war</packaging> 
	<version>0.0.1-SNAPSHOT</version> 
	<name>TVShow</name> 
	<url>http://maven.apache.org</url> 
	<properties> 
		<failOnMissingWebXml>false</failOnMissingWebXml> 
		<spring-version>5.1.0.RELEASE</spring-version> 
	</properties> 
	<dependencies> 
		
		<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
		<dependency> 
			<groupId>org.springframework</groupId> 
			<artifactId>spring-webmvc</artifactId> 
			<version>${spring-version}</version> 
		</dependency> 
		
		<!-- Required for spring-test -->
		<dependency> 
			<groupId>org.springframework</groupId> 
			<artifactId>spring-test</artifactId> 
			<version>${spring-version}</version> 
		</dependency> 

		<!-- JSTL Dependency -->
		<dependency> 
			<groupId>javax.servlet.jsp.jstl</groupId> 
			<artifactId>javax.servlet.jsp.jstl-api</artifactId> 
			<version>1.2.1</version> 
		</dependency> 
		
		<dependency> 
			<groupId>taglibs</groupId> 
			<artifactId>standard</artifactId> 
			<version>1.1.2</version> 
		</dependency> 

		<!-- Servlet Dependency -->
		<dependency> 
			<groupId>javax.servlet</groupId> 
			<artifactId>javax.servlet-api</artifactId> 
			<version>3.1.0</version> 
			<scope>provided</scope> 
		</dependency> 

		<!-- JSP Dependency -->
		<dependency> 
			<groupId>javax.servlet.jsp</groupId> 
			<artifactId>javax.servlet.jsp-api</artifactId> 
			<version>2.3.1</version> 
			<scope>provided</scope> 
		</dependency> 
		
		<!-- As REST API is extracted, this is required -->
		<dependency> 
			<groupId>com.google.code.gson</groupId> 
			<artifactId>gson</artifactId> 
			<version>2.8.6</version> 
		</dependency> 
		<dependency> 
			<groupId>commons-io</groupId> 
			<artifactId>commons-io</artifactId> 
			<version>2.5</version> 
		</dependency> 
		<dependency> 
			<groupId>junit</groupId> 
			<artifactId>junit</artifactId> 
			<version>4.12</version> 
			<scope>test</scope> 
		</dependency> 
	</dependencies> 
	<build> 
		<finalName>TVShow</finalName> 
		<sourceDirectory>src/main/java</sourceDirectory> 
		<plugins> 
			<plugin> 
				<artifactId>maven-compiler-plugin</artifactId> 
				<version>3.5.1</version> 
				<configuration> 
					<source>1.8</source> 
					<target>1.8</target> 
				</configuration> 
			</plugin> 
			
			<plugin> 
<groupId>org.apache.maven.plugins</groupId> 
<artifactId>maven-war-plugin</artifactId> 
<version>3.3.2</version> 
</plugin> 

	<plugin> 
		<groupId>org.codehaus.mojo</groupId> 
		<artifactId>tomcat-maven-plugin</artifactId> 
		<version>1.0-beta-1</version> 
	</plugin> 
		</plugins> 
		
	</build> 
</project>

 index.jsp 編寫:

這是項目部署到tomcat時渲染的頁面

<!DOCTYPE html> 
<html lang="en"> 
<head> 
	<meta charset="utf-8"> 
	<meta http-equiv="X-UA-Compatible" content="IE=edge"> 
	<meta name="viewport" content="width=device-width, initial-scale=1"> 
	<title>TVShow</title> 
	<link rel="stylesheet" > 
	<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> 
	<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script> 
	// for making the page styles are applied 
	<style type="text/css"> 
		.main-form, .profile-area { 
			width: 500px; 
		} 
		.main-form { 
			margin: 50px auto 0px; 
		} 
		.profile-area { 
			margin: 10px auto; 
		} 
		.main-form section, .profile-area section { 
			margin-bottom: 15px; 
			background: #097969; 
			box-shadow: 0px 2px 2px rgba(0, 0, 0, 0.3); 
			color: white; 
		} 
		.main-form section { 
			padding: 30px; 
		} 
		.profile-area section { 
			padding: 30px 30px 30px; 
		} 
		.profile-area section > div { 
			text-align: center; 
		} 
		.main-form h3 { 
			margin: 0 0 15px; 
		} 
		.form-control, .btn { 
			min-height: 38px; 
			border-radius: 2px; 
		} 
		.btn { 
			font-size: 15px; 
			font-weight: bold; 
		} 
		.hideElement { 
			display: none; 
		} 
	</style> 
</head> 
<body> 
<div class="main-form" id="main-form"> 
	<section> 
		<div class="form-group"> 
			// We need to input the search string in this box 
			<input id="searchStr" type="text" class="form-control" placeholder="Enter TVShow name here..." required="required"> 
		</div> 
		<div class="form-group"> 
			<button onclick="loadData()" class="btn btn-primary btn-block">Find TVShow Details</button> 
		</div> 
	</section> 
</div> 
<div class="profile-area hideElement" id="profile-area"> 
	<section> 
		<div id="loader" class="hideElement"> 
			<div class="spinner-border" role="status"> 
				<span class="sr-only">Loading...</span> 
			</div> 
		</div> 
		<div id="profile" class="hideElement"> 
			<br><br> 
			// parsed json object details are displayed here 
			
<p><strong>TVShowScore : </strong><span id="scores"></span></p> 

			
<p><strong>TVShow URL : </strong><span id="url"></span></p> 

			
<p><strong>IMDB : </strong><span id="imdb"></span></p> 

		</div> 
	</section> 
</div> 
</body> 
<script> 
	function loadData() { 
		document.getElementById("profile-area").classList.remove("hideElement"); 
		document.getElementById("loader").classList.remove("hideElement"); 
		document.getElementById("profile").classList.add("hideElement"); 

		var searchStr = document.getElementById("searchStr").value; 

		if(searchStr != "" && searchStr != null ) { 
			var xhttp = new XMLHttpRequest(); 
			xhttp.onreadystatechange = function() { 
				if (this.readyState == 4 && this.status == 200) { 
					var jsonResponse = JSON.parse(this.responseText); 
					document.getElementById("scores").innerHTML = jsonResponse.scores; 
					document.getElementById("url").innerHTML = jsonResponse.url; 
					document.getElementById("imdb").innerHTML = jsonResponse.imdb; 
					document.getElementById("loader").classList.add("hideElement"); 
					document.getElementById("profile").classList.remove("hideElement"); 
				} 
			}; 
			// GET method which redirects the jsp to connect to 
			// the servlet with the search string 
			xhttp.open("GET", "getTVShowDetailsBySearchString?searchStr="+ searchStr, true); 
			xhttp.send(); 
			console.log("done"); 
		} else { 
			console.log("Enter search string to check...") 
		} 
	} 
</script> 
</html>
-----------------------------------
?著作權歸作者所有:來自51CTO博客作者demo007x的原創作品,請聯系作者獲取轉載授權,否則將追究法律責任
如何通過 REST API 和 Spring MVC 提取電視節目詳細信息?
https://blog.51cto.com/demo007x/7917153

輸出:

在輸入框中輸入任何電視節目名稱后,我們將獲得以下詳細信息。

執行過程:

從 JSP 頁面,使用搜索字符串調用“GET”方法,并將其重定向到 Spring Controller 類,其中 REST API URL http://api.tvmaze.com/search/shows?q= 被調用,它將創建上面給出的 JSON 數組,從中,我們使用下面的參數:

"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 輸出所需的代碼如下。實現流程的重要必要文件

AppConfig.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:

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[] { "/" }; 
	} 

}

TVShowController.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<JsonElement> 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=<searchstring> 
		// 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; 
	} 
}
-----------------------------------
?著作權歸作者所有:來自51CTO博客作者demo007x的原創作品,請聯系作者獲取轉載授權,否則將追究法律責任
如何通過 REST API 和 Spring MVC 提取電視節目詳細信息?
https://blog.51cto.com/demo007x/7917153

結論

通過使用 Spring-webmvc,我們可以從 REST API 調用中獲取詳細信息。上面就是一個很好的例子。同樣,有很多開源 REST API 調用可供使用。這意味著我們可以使用它們來檢索數據。開源 REST API 調用的幾個示例。

責任編輯:龐桂玉 來源: 51CTO博客
相關推薦

2011-09-19 10:32:54

IOS應用Android應用Spott

2010-06-22 10:10:18

超算“沃森”美國電視節目

2014-06-20 10:36:49

微軟Windows Azu創客星球

2011-01-28 15:26:34

深藍人機大戰沃森

2014-07-11 10:11:59

OTT機頂盒

2020-12-14 12:39:43

數據分析Netflix詞匯

2012-05-14 10:49:25

Cloud Found

2016-01-07 13:52:17

Windows 10登錄顯示

2020-05-15 07:00:00

Linux硬盤信息

2010-11-09 11:54:50

sql server查

2020-07-07 07:00:00

Spring WebFREST APIReactive AP

2014-12-09 13:06:30

華為移動公交

2020-08-23 18:22:15

網絡

2020-12-04 06:14:45

5G 廣電 通信網絡

2013-11-05 10:18:48

2013-11-05 10:01:45

2023-05-11 12:40:00

Spring控制器HTTP

2019-08-26 11:53:38

Linux系統GUI

2013-02-01 10:09:46

TV客

2010-09-02 15:39:08

點贊
收藏

51CTO技術棧公眾號

主站蜘蛛池模板: 欧美精品第一区 | 在线观看国产视频 | 欧美色视频免费 | 在线精品亚洲欧美日韩国产 | 色频| 无码日韩精品一区二区免费 | 久久久成 | 日韩精品在线一区二区 | 中文字幕欧美一区二区 | 精品国产欧美一区二区三区成人 | 日韩视频一区 | 欧美成人免费 | 亚洲精品乱 | 国产福利在线视频 | 成人免费视频观看视频 | yiren22综合网成人 | 国产欧美精品在线观看 | 欧美αv| 久久久做 | www.久久久.com| 国产美女在线精品免费 | 日日夜夜av | 黄色一级视频免费 | 国产99久久精品一区二区永久免费 | 国产精品免费在线 | 毛片.com | 久久国产一区二区三区 | 色五月激情五月 | 国产精品三级久久久久久电影 | www国产成人免费观看视频,深夜成人网 | 国产色网| 亚洲精品乱码久久久久久按摩观 | 91久久网站 | 五十女人一级毛片 | 欧美一区二区三区四区视频 | 日日骑 | 玖玖综合在线 | 午夜视频在线观看一区二区 | 欧美一区二区成人 | 中文字幕免费中文 | 国产综合区 |