Java Quickstart | YouTube Data API - Google Developers

文章推薦指數: 80 %
投票人數:10人

Java Quickstart · You will use an API key, which identifies your application, to retrieve information about the GoogleDevelopers YouTube channel. YouTube DataAPI Language English BahasaIndonesia Deutsch Español Français Português–Brasil Русский 中文–简体 日本語 한국어 Signin Home Guides Reference Samples Support YouTube DataAPI Home Guides Reference Samples Support Overview ClientLibraries AuthorizeRequests OverviewGetAuthCredentialsServer-sideWebAppsClient-sideWebAppsInstalledAppsDevices Quickstarts AndroidAppsScriptGoiOSJavaJavaScriptNode.jsPHPPythonRuby GuidesandTutorials QuotacostsforAPIrequestsQuotaandComplianceAuditsUploadaVideoSendResumableUploadsFindMadeForKidsvideostatusSubscribetoPushNotificationsWorkwithChannelIDsMovefromClientLogintoOAuth SampleRequests ImplementationGuide OverviewActivitiesCaptionsChannelsCommentsPaginationPartialresponsesPlaylistsRatingsSearchrequestsSubscriptionsVideos Tools APIsExplorer Home Products YouTube DataAPI Guides JavaQuickstart Thisquickstartguideexplainshowtosetupasimple,Java command-lineapplicationthatmakesrequeststotheYouTubeDataAPI.This quickstartactuallyexplainshowtomaketwoAPIrequests: YouwilluseanAPIkey,whichidentifiesyourapplication,to retrieveinformationabouttheGoogleDevelopersYouTubechannel. YouwilluseanOAuth2.0clientIDtosubmitanauthorizedrequest thatretrievesinformationaboutyourownYouTubechannel. Note:Moregenerally,youcanfollowtheinstructionsforthefirstexample foranyusecasethatusesanAPIkeyortheinstructionsforthesecond exampleforanyusecasethatrequiresauthorizationusingOAuth2.0.Seethe usecasesandcodesamplestoolfor moreexamples. Prerequisites Torunthisquickstart,you'llneed: Java1.7orgreater. Gradle2.3orgreater. Accesstotheinternetandawebbrowser. AGoogleaccount. Step1:Setupyourprojectandcredentials CreateorselectaprojectintheAPIConsole.CompletethefollowingtasksintheAPIConsoleforyourproject: Inthelibrarypanel, searchfortheYouTubeDataAPIv3.ClickintothelistingforthatAPIand makesuretheAPIisenabledforyourproject. Inthecredentials panel, createtwocredentials: CreateanAPIkey YouwillusetheAPIkeytomakeAPIrequeststhatdo notrequireuserauthorization.Forexample,youdonotneeduser authorizationtoretrieveinformationaboutapublicYouTubechannel. CreateanOAuth2.0clientID SettheapplicationtypetoOther.YouneedtouseOAuth2.0 credentialsforrequeststhatrequireuserauthorization.Forexample, youneeduserauthorizationtoretrieveinformationaboutthecurrently authenticateduser'sYouTubechannel. DownloadtheJSONfilethatcontainsyourOAuth2.0credentials.The filehasanamelikeclient_secret_CLIENTID.json,whereCLIENTIDis theclientIDforyourproject. Step2:Preparetheproject CompletethefollowingstepstoprepareyourGradleproject: Inyourworkingdirectory,runthefollowingcommandstocreateanew projectstructure: $gradleinit--typebasic $mkdir-psrc/main/javasrc/main/resources MovetheJSONfilethatyoudownloadedaftercreatingyourOAuth2.0client IDtothesrc/main/resourcesdirectorybelowyourworkingdirectory,and renamethefiletoclient_secret.json. Openthebuild.gradlefileinyourworkingdirectoryandreplaceits contentswiththefollowing: applyplugin:'java' applyplugin:'application' mainClassName='ApiExample' sourceCompatibility=1.7 targetCompatibility=1.7 version='1.0' repositories{ mavenCentral() } dependencies{ compile'com.google.api-client:google-api-client:1.23.0' compile'com.google.oauth-client:google-oauth-client-jetty:1.23.0' compile'com.google.apis:google-api-services-youtube:v3-revREVISION-CL_VERSION' } Inthebuild.gradlefile,youneedtoreplacethe REVISIONandCL_VERSIONvariableswithtwovaluesfrom theclientlibrary documentation fortheYouTubeDataAPI.Thescreenshotbelow,whichshowsthe documentationfortheYouTubeAnalyticsAPI,showswherethetwovariables appearonthepage. Step3:Setupandrunthesample UsetheAPIsExplorerwidgetinthesidepaneltoobtainsamplecodefor retrievinginformationabouttheGoogleDevelopersYouTubechannel.Thisrequest usesanAPIkeytoidentifyyourapplication,anditdoesnotrequireuser authorizationoranyspecialpermissionsfromtheuserrunningthesample. OpenthedocumentationfortheAPI's channels.listmethod. Onthatpage,the"Commonusecases"sectioncontainsatablethatexplains severalcommonwaysthatthemethodisused.Thefirstlistinginthetable isforlistingresultsbychannelID. Clickthecodesymbolforthefirstlistingtoopenandpopulatethe fullscreenAPIsExplorer. TheleftsideofthefullscreenAPIsExplorershowsthefollowing: BelowtheRequestparametersheader,thereisalistofparameters thatthemethodsupports.Thepartandidparametervaluesshould beset.Theidparametervalue,UC_x5XG1OV2P6uZZ5FSM9Ttw,isthe IDfortheGoogleDevelopersYouTubechannel. Belowtheparameters,thereisasectionnamedCredentials.The pulldownmenuinthatsectionshoulddisplaythevalueAPIkey.The APIsExplorerusesdemocredentialsbydefaulttomakeiteasiertoget started.Butyou'lluseyourownAPIkeytorunthesamplelocally. TherightsideofthefullscreenAPIsExplorershowstabswithcodesamples indifferentlanguages.SelecttheJavatab. Copythecodesampleandsaveitinafilenamed src/main/java/ApiExample.java. Everysampleusesthesameclassname(ApiExample)sothatyoudon't needtomodifythebuild.gradlefiletorundifferentsamples. Inthesamplethatyoudownloaded,findtheYOUR_API_KEYstringand replacethatwiththeAPIkeythatyoucreatedinstep1ofthisquickstart. Runthesamplefromthecommandline.Inyourworkingdirectory,run: gradle-qrun ThesampleshouldexecutetherequestandprinttheresponsetoSTDOUT. Step4:Runanauthorizedrequest Inthisstep,you'llmodifyyourcodesamplesothatinsteadofretrieving informationabouttheGoogleDevelopersYouTubechannel,itretrievesinformation aboutyourYouTubechannel.Thisrequestdoesrequireuserauthorization. GobacktothedocumentationfortheAPI's channels.listmethod. Inthe"Commonusecases"section,clickthecodesymbolforthethird listinginthetable.Thatusecaseistocallthelistmethodfor"my channel." Again,intheleftsideofthefullscreenAPIsExplorer,youwillseea listofparametersfollowedbytheCredentialssection.However,there aretwochangesfromtheexamplewhereyouretrievedinformationaboutthe GoogleDeveloperschannel: Intheparameterssection,insteadoftheidparametervaluebeing set,themineparametervalueshouldbesettotrue.Thisinstructs theAPIservertoretrieveinformationaboutthecurrentlyauthenticated user'schannel. IntheCredentialssection,thepulldownmenushouldselectthe optionforGoogleOAuth2.0. Inaddition,ifyouclicktheShowscopeslink,the https://www.googleapis.com/auth/youtube.readonlyscopeshouldbe checked. Aswiththepreviousexample,selecttheJavatab, copythecodesample,andsaveittosrc/main/java/ApiExample.java. Runthesamplefromthecommandline.Inyourworkingdirectory,run: gradle-qrun Thesampleshouldattempttoopenanewwindowortabinyourdefault browser.Ifthisfails,copytheURLfromtheterminalandmanuallyopenit inyourbrowser. IfyouarenotalreadyloggedintoyourGoogleaccount,youwillbe promptedtologin.IfyouareloggedintomultipleGoogleaccounts,you willbeaskedtoselectoneaccounttousefortheauthorization. Clickthebuttontograntyourapplicationaccesstothescopesspecifiedin yourcodesample. Thesamplewillproceedautomatically,andyoumayclosethebrowsertab usedfortheauthflow. TheAPIresponseshouldagainbeprintedtoSTDOUT. Furtherreading GoogleDevelopersConsolehelpdocumentation GoogleAPIsClientLibraryforJavadocumentation YouTubeDataAPIJavadocdocumentation YouTubeDataAPIreferencedocumentation Exceptasotherwisenoted,thecontentofthispageislicensedundertheCreativeCommonsAttribution4.0License,andcodesamplesarelicensedundertheApache2.0License.Fordetails,seetheGoogleDevelopersSitePolicies.JavaisaregisteredtrademarkofOracleand/oritsaffiliates. Lastupdated2019-06-11UTC. [{ "type":"thumb-down", "id":"missingTheInformationINeed", "label":"MissingtheinformationIneed" },{ "type":"thumb-down", "id":"tooComplicatedTooManySteps", "label":"Toocomplicated/toomanysteps" },{ "type":"thumb-down", "id":"outOfDate", "label":"Outofdate" },{ "type":"thumb-down", "id":"samplesCodeIssue", "label":"Samples/codeissue" },{ "type":"thumb-down", "id":"otherDown", "label":"Other" }] [{ "type":"thumb-up", "id":"easyToUnderstand", "label":"Easytounderstand" },{ "type":"thumb-up", "id":"solvedMyProblem", "label":"Solvedmyproblem" },{ "type":"thumb-up", "id":"otherUp", "label":"Other" }] Blog ThelatestnewsontheYouTubeblog GitHub FindAPIcodesamplesandotherYouTubeopen-sourceprojects. IssueTracker Somethingwrong?Sendusabugreport! StackOverflow Askaquestionundertheyoutube-apitag Videos CheckouttheYouTubeDeveloperRelationsteam'sYouTubechannel Tools GoogleAPIsExplorer YouTubePlayerDemo ConfigureaSubscribeButton IssueTracker Fileabug Requestafeature Seeopenissues ProductInfo TermsofService BrandingGuidelines MonetizationGuidelines APIssubjecttoDeprecationPolicy Android Chrome Firebase GoogleCloudPlatform Allproducts Terms Privacy SignupfortheGoogleDevelopersnewsletter Subscribe Language English BahasaIndonesia Deutsch Español Français Português–Brasil Русский 中文–简体 日本語 한국어



請為這篇文章評分?