




下载本文档
版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
时间轴API接入和管理项目通过HTTP的REST操作时间表。(Youruser'stimelineisdividedupintotimelineitems.YoucanusetheAPItoinsertandmanagetimelineitemswithRESToperationsoverHTTP.)注意:30API。(NoteTimelineitemslastforsevendaysonauser'sGlassand30daysintheMirrorAPI.)卡要插入一个时间表项,POSTJSON表示的时间表项目的REST个简单的时间表项目如何入。(Toinsertatimelineitem,POSTaJSONrepresentationofatimelineitemtotheRESTendpoint.Mostofthefieldsareoptional.Insimplestform,atimelineitemcontainsonlyashorttextmessage.Thisishowasimpletimelineitemisinserted.)原始HTTP的JavaPOST/mirror/v1/timelineHTTP/1.1Authorization:Bearer{authtoken}Content-Type:application/jsonContent-Length:26{"text":"oworld"JavaTimelineItemtimelineItem=newTimelineItem();timelineItem.setText("oworld");201响应代码创建创建项目的完整副本。对于上面的例子,可能看起来像一个成功的响应:(Onsuccess,theserverwillreturna201CreatedresponsecodewithafullcopyofthecreateditemFortheexampleabove,asuccessfulresponsemightlook原始的HTTP/1.1HTTP/1.1201Date:Tue,25Sep201223:30:11Content-Type:application/jsonContent-Length:303{"kind":"glass#timelineItem","id":" "selfLink":"etag":"\"G5BI0RWvj-0jWdBrdWrPZV7xPKw/t25selcGS3uDEVT6FB09hAG-QQ\"","text":" oworld"}插入项目,将出现在用户的时间轴看起来像这样:(Theinserteditemthatwouldappearintheuser'stimelinelookslikethis:)阅读时间表项目(Readingtimeline你的服务可以所有的时间表,它创建项目,以及所有共享项目时间表。以下是如何为您服务是可见的项目列出时间表。(Yourservicecanaccessalltimelineitemsthatitcreated,andalltimelineitemsthatweresharedwithit.Here'showtolistthetimelineitemsthatarevisibletoyourservice.)原始HTTPGET/mirror/v1/timelineHTTP/1.1Authorization:Bearer{authJavaTimelineItemtimelineItem=new您可以使用其他REST(YoucanuseotherRESToperationstoget,updateanddeletetimelineitems.)插入一个时间表与项目(Insertingatimelineitemwith像和作为附件的时间表项目。(Apictureisworthathousandwords,whichisalotmorethanyoucanfitintoatimelineitem.Tothisend,youcanalsoincludeimagesandasattaentstoatimelineitem.)在一个较低的水平,使用HTTP多附件上传。谷歌的API客户端库,使得这个易于使用的上传。(Atalowlevel,attaentsareuploadedusingHTTPMultipart.APIslibrariesmakethiseasyusingmediaupload.)以下是如何插入一个时间表带有附件的项目。(Here'showtoinsertatimelineitemwithan原始HTTP的Java的POSTPOST/mirror/v1/timelineHTTP/1.1Authorization:Bearer{authContent-Type:multipart/related;boundary="mymultipartboundary"Content-Length:{length}--{"text":"AsolareclipseofSaturn.Earthisalsointhisphoto.Canyoufindit?"Content-Type:image/jpeg[binaryimageTimelineItemtimelineItem=newTimelineItem(); oworld");InputStreamContentmediaContent=newInputStreamContent(contentType,atta service.timeline().insert(timelineItem,mediaContent).execute();时间轴项附加图像的玻璃装置上,看起来像这样:(Atimelineitemwithanattachedimagelookssomethinglikethisontheglassdevice:)附件(AccessingattaURLcontentUrl属性或通过附件的端点。(Timelineitemswith entsexposetheminanarraypropertyaptlynamedatta ents.Thebinarydatafortheatta entcanbefetchedfromtheURLfoundinthecontentUrlpropertyorviatheattaentsendpoint.)注:内容保护的OAuth2.0,就像其他调用的API端点。谷歌API客户端库提供附件使功能的二进制内容。(Note:ThecontentisprotectedbyOAuth2.0,justlikeothercallstotheAPIendpoints.APIlibrariesprovideaccesstothebinarycontentofattaentsusingthemediadownloadfeature.)原料HTTPentId= StringJAVATimelineItemitem=entId}GET/mirror/v1/timeline/{itemId}/attaAuthorization:Bearer{auth卡(Bundlingallowsyoutocombinemanyrelatedcardsintoabundle.Bundlesaredistinguishedfromnormaltimelinecardsbythepagecurlintheupperrightcorner.)有两种方式内容:寻呼和线程。寻呼是通过指定值在timelineItem.htmlPages[]属性。如果使用分页,元素都有着相同的timelineId,因此有相同的一组菜单项。这是非常有用的内容传送至玻璃不适合到一个单一的卡。(Therearetwowaystobundlecontent:pagingandthreading.PagingisdonebyspecifyingvaluesinthetimelineItem.htmlPages[]property.Ifyouusepagingbundles,elementsallsharethesametimelineIdandhencehavethesamesetof items.ThisisusefulforsendingcontenttoGlassthatdoesnotfitontoasinglecard.)bundleId的许多时间表卡关联。要使用此技术,创造相同的值bundleId许多时间表项目。最近新增的项目将被盖卡。这种技术更可用于相关项目,如电子邮件线程。(ThreadingisdonebyassociatingmanytimelinecardswithacommonbundleId.Tousethistechnique,createmanytimelineitemswiththesamevalueforbundleId.Themostrecentlyaddeditemwillbethecovercard.Thistechniqueismoreusefulforrelateditemslike 用户交互菜单项(Userin ctionwith菜单项时间表卡。(DeliveringcontentisonlyhalfofthestoryMostinterestingservicesalsorespondtoactionstakenbytheuser.Userscanactontimelinecardsbyselecting时间表卡所提供的特殊功能,导航到一个位置或者共享图像。(itemscomeintwoflavors:built-in itemsandcustom items.Built-in itemsprovideaccesstospecialfunctionalitiesprovidedbytheglassdevicehardwaresuchasreadingatimelinecardaloud,navigatingtoalocationorsharinganimage.) itemsallowyourapplicationtoexposebehaviorthatisspecifictoyourserviceandprovidea icontomatch)使用内置的菜单项(Usingbuilt- 您可以添加内置菜单项,通过填充菜单项数组,当你插入你的时间表项目。要使用一个内置的菜单项,你只需要填入每个菜单项的动作。(Youcanaddbuilt-in itemstoyourtimelineitemsbypopulatingtheItemsarraywhenyouinsertthem.Touseabuilt-initem,youonlyneedtopopulatetheactionofeachItem.)原始的HTTP/1.1HTTP/1.1201Date:Tue,25Sep201223:30:11Content-Type:application/jsonContent-Length:303{"text":" oworld", Items":[{"action":}]}注:参考文档包含可用的内建动作的详细说明。(Note:Thereferenceationcontainsadetaileddescriptionoftheavailablebuiltinactions.)定义自定义菜单项(Definingcustom来发挥作用。(Built-inactionsmaynotalwaysbeenough.Manyservicesneedtoexposetheirownspecificitems.Thisiswherecustomactionscomeintoy.)(CreateacustomitembyspecifyingaItem.actionofCUSTOMandaItem.id.Whenyourusertriggersoneofyourcustomitems,anotificationissenttoyourservicewiththeItem.idpopulated.Thisallowsyoutodeterminethesourceofthenotification.)您还必须填充Item.Value的指定iconUrl和显示名称将出现在玻璃设备。(YoumustalsopopulateItem.ValuetospecifyaniconUrlanddisyNamethatwillappearontheglassdevice.)原始的HTTP/1.1HTTP/1.1201Date:Tue,25Sep201223:30:11Content-Type:application/jsonContent-Length:303{"text":" o"text":" oworld", Items":[{"action":"id":"values": yName":"Complete","iconUrl":"}]}:results,useaPNGiconimagethatis50pixelssquarewithatransparent允许用户固定时间表卡(Allowinguserstopinyourtimeline左侧。用户可以取消固定卡,通过使用相同的菜单项。(Youcancreateaitemthatletsyouruserspinthetimelinecard,whichpermanentlydisysthetimelinecardtotheleftofthemainclockcard.Userscanunpinthecardaswell,byusingthesameitem)TOGGLE_PINNED行动。(Thepinningitemisabuilt-initem,soallyouneedtodoisprovidetheTOGGLE_PINNEDactionforaItem.)原始的HTTP/1.1HTTP/1.1201Date:Tue,25Sep201223:30:11Content-Type:application/jsonContent-Length:303{"text":"Youcanpinorunpinthiscard.", Items":[{"action":}]]}API。(TheMirrorAPIallowsyoutosubscribetonotificationsthataresentwhentheusertakesspecificactionsonaTimelineItemorwhentheuserlocationhasbeenupdated.)接收通知(Receiving从镜像API发送一个POST请求包含一个JSON请求主体的端点。(AnotificationfromtheMirrorAPIissentasaPOSTrequesttothesubscribedendpointcontainingaJSONrequest原始HTTP{}"collection":"itemId":"3hidvm0xez6r8_dacdb3103b8b604_h8rpllg","operation":"UPDATE","userToken":"verifyToken":"random_hash_to_verify_referer","userActions":[{"type":"payload":}]Javaimportimportimportcom.import.api.servicesimportjava.io.IOException;importjava.io.InputStream;//publicclassMyClass//ParsearequestbodyintoaNotification*@paramrequestBodyThenotificationpayloadsentbytheMirror@returnParsednotificationpayloadifsuccessful,{@codenull}staticNotificationparseNotification(InputStreamrequestBody){try{JsonFactoryjsonFactory=new}catch(IOExceptione){System.out.println("Anerroroccurred:"+e);returnnull;}}//}200OKHTTP状态代码,如果没有发生错误的API。如果您的服务响API可能会尝试重新发送该通知为您服务。(YourservicemustrespondtotheAPIwitha200OKHTTPstatuscodeifnoerroroccurred.Ifyourservicerespondswithanerrorcode,theMirrorAPImighttrytoresendthenotificationtoyourservice.)注:10秒后。如果需要一个漫长的过程,马上做出反应,并在另一个线程中做的过程。(Note:Theconnectionwilltimeoutafter10seconds.Ifalongprocessisrequired,respondrightawayanddotheprocessinanotherthread.)通知类型(Notification镜API发送一个不同的有效载荷为不同的通知。(TheMirrorAPIsendsadifferentnotificationpayloadfordifferentevents.)共享(Shared用户已经了一张与您的服务。(Theuserhassharedapicturewithyour{{"collection":"itemId":"3hidvm0xez6r8_dacdb3103b8b604_h8rpllg","operation":"UPDATE","userToken":"verifyToken":"random_hash_to_verify_referer","userActions":[{"type":}]}{{"id":"3hidvm0xez6r8_dacdb3103b8b604_h8rpllg", ents":[{"id": }"recipients":{"kind":"glass#contact","source":"api:<SERVICE_ID>","id":"<CONTACT_ID>", yName": "imageUrls":[]}] 作为附件的ID:(TheitemIdattributeissettotheIDtheitemcontainingthephotoasan }} 信息,请参阅联系。(Note:SeeContactsformoreinformationaboutsharingcontentwithcontacts.){"collection":"itemId":"3hidvm0xez6r8_dacdb3103b8b604_h8rpllg","operation":"INSERT","userToken":"verifyToken":"random_hash_to_verify_referer","userActions":[{"type":{"collection":"itemId":"3hidvm0xez6r8_dacdb3103b8b604_h8rpllg","operation":"INSERT","userToken":"verifyToken":"random_hash_to_verify_referer","userActions":[{"type":}]}文本属性设置文本transcribtion附件的属性设置到Web的音频器和语音记录的音频文件(TheitemIdattributeissettotheIDoftheiteminReplyToattributesettotheIDofthetimelineitemitisareplytextattributesettothetextattaentsattributesettothewebaudioyerandtheaudiofileofthevoice{{"kind":"id":"3hidvm0xez6r8_dacdb3103b8b604_h8rpllg","inReplyTo":"3236e5b0-b282-4e00-9d7b-6b80e2f47f3d","text":"Thisisatextreply", ents":{ {}]}删该用户已删除项目的时间表:(Theuserhasdeletedatimeline{{"collection":"itemId":"3hidvm0xez6r8_dacdb3103b8b604_h8rpllg","operation":"DELETE","userToken":"verifyToken":"random_hash_to_verify_referer","userActions":[{"type":}]}ITEMID属性设置的ID删除项。资料不再包含元数据以外的IDisDeleted财产的。(TheitemIdattributeissettotheIDofthedeleteditem.TheitemnolongercontainsmetadataotherthanitsIDandtheisDeletedproperty.)注意:如果用户删除一个项目从他们的时间表,建议您删除这些内容从你的系统太。(Note:Iftheuserdeletesanitemfromtheirtimeline,it's mendedthatyoudeletethiscontentfromyoursystems选择自定义菜单项(Customitem{"collection":"itemId":(Theuserhasselecteda{"collection":"itemId":"operation":"UPDATE","userToken":"operation":"UPDATE","userToken":"harold_penguin","userActions":[{"type":"payload": }]}的ITEMID属性被设置为用户选择的菜单项的ID。(TheitemIdattributeissettotheIDof itemthattheuserselected.)应的行动。(TheuserActionsarraycontainsthelistofcustomactionsthattheusertookonthisitem.Yourserviceshouldhandlethoseactionsaccordingly.)位置更新(Location为当前用户提供一个新的位置是:(Anewlocationisavailableforthecurrent {"collection":"locations","itemId":"latest","operation":"UPDATE","userToken":}置。10分钟更新。(WhenyourGlasswarereceivesalocationupdate,sendarequesttotheglass.locations.getendpointtoretrievethelatestknownlocation.YourGlasswarereceiveslocationupdateseverytenminutes.)注正在位置信息需要 (Note:Retrievinglocation the API性位置更新。您也可以提供预渲染的时间表卡给镜像API坐标绘制的地图图像。(YoucanusetheMirrorAPItoobservetheuser'slocationintimelineitems,requesttheirlastknownlocationdirectly,andsubscribetoperiodiclocationupdates.Youcanalsodeliverpre-renderedmapimagesintimelinecardsbygivingtheMirrorAPIthecoordinatestodraw.)注:检索用户的位置,需要外https://w /auth/glass.location范围。(Note:Retrievingusers'locationrequiresthe 检索的已知位置(Retrievingthelatestknown要检索的已知位置为当前用户,发送一个GET请求发送到REST端点:(Toretrievethelatestknownlocationforthecurrentuser,sendaGETrequesttotheRESTendpoint:)原始的GETGET/mirror/v1/locations/HTTP/1.1Authorization:Bearer{authtoken}订阅的位置更新(Subscribingtolocation(Similartosubscribingtotimelineupdates,youcansubscribetolocationupdatesbysubscribingtothelocationscollection.)原始的POSTPOST/mirror/v1/subscriptionsHTTP/1.1Authorization:Bearer{authtoken}Content-Type:application/jsonContent-Length:{"collection":"locations","userToken":"harold_penguin","verifyToken":"random_hash_to_verify_referer","callbackUrl":"h }注:10分钟发送。(NoteAtthistimelocationnotificationsaresentevery10minutes.)在时间轴卡的渲染图(RenderingmapsontimelineAPI可以使你和覆盖标记和线条图,以示重要场所和路径。使用玻璃URI请求地图。下面是一个例子:(TheMirrorAPIcanrendermapsforyouandoverlaymarkersandlinestosignifyimportantcesandpaths.Usetheglass://mapURItorequestamap.Here'sanexample:)这里是一个所需的参数的描述:(NoteAlwaysspecifythewidthandheightoftheimageinthe<imgtagaswell.Thispreventsreflowsasthemapimageisbeingrendered.)Hereisadescriptionofrequired另外需要在下面的列表中只有一个项目,但您可以指定所有的人:(Onlyoneoftheitemsinthefollowinglistareadditionallyrequired,butyoucanspecifyallofthem:)(centerandzoomThecenterlatitude,longitudeofthemaptorenderatandthezoomlevel.SeeZoomLevelsformoreinformation.)标记-指定的引脚标记绘制在指定的坐标。标记参数采用标记(从0开始),纬度坐标和经围。(markerSpecifythepinmarkerstodrawatthespecifiedcoordinates.Themarkerparametertakesanindexvalueforthemarker(startingat0thelatitudecoordinateandthelongitudecoordinateThemapautomaticallycentersandzoomsaroundthemarkersyoucreateifyoudon'texplicitlyspecifycenterandzoom.)-8个像素宽的红线之间(47.6,-122.34)和(47.62,-122.40)=8,FFFF000047.6,-122.34,47.62,-122.40指定。地图会自动居中并缩放到适合的折线,如果你不明确指定中心和缩放。(polyline-Specifythepolylinecoordinatestorepresentapathonthemap.Eachpolylineconsistsofawidthandcolorfollowedbytheverticesinthepolyline.Forexample:polyline=8,ffff0000;47.6,-122.34,47.62,-122.40specifiesan8-pixelwideredlinebetween(47.6,-122.34)and122.40).Themapisautomaticallycenteredandzoomedtofitthepolylineifyoudon'texplicitlyspecifycenterandzoom.)下面的示例显示如何显示一些文本,它是什么样子的地图图像的最佳实践:(Thefollowingexampleshowsabestpracticeofhowtodisyamapimagewithsometextandwhatitlookslike:)<img<pclass="yellow">12minutestohome</p><p>Mediumtrafficon注您可以省略折线的颜色和宽度,在这个例子中一样。地图渲染,在这种情况下,使用默认的颜色和宽度。(NoteYoucanomitthecolorandwidthofthepolylinelikeinthisexample.Themapisrenderedusingthedefaultcolorandwidthinthissituation.)默认情况下,玻璃器皿有时间表的项目,它创建的。联系,结合内置菜单项,允许用项目创建的项目,如内置的头所拍摄的。(Bydefault,Glasswareonlyhasaccesstothetimelineitemsthatitcreated.Contacts,combinedwiththeSHAREbuilt-initem,allowyouruserstosharetimelineitemswithotherGlassware.ThisincludesbothtimelineitemscreatedbyotherGlasswareandtimelineitemscreatedbythedeviceitself,suchasphotostakenbythebuilt-incamera.)为了让用户你的玻璃器皿时间表项目,通过发布一个JSON表示接触到插入REST端点插(ToallowtheusertosharetimelineitemswithyourGlasswareinsertacontactbyPOSTingaJSONrepresentationofacontacttotheinsertRESTendpoint.)IDimageUrls,用于当接触,这将在玻璃的移动设备上显示。(Allcontactsmustspecifyanid,whichidentifiesthecontacttotheGlasswarereceivingthenotifications.YoumustalsospecifyadisyNameandatleastoneimageUrls,whichwillbedisyedontheGlassdevicewhenthecontactisused.)原始的POSTPOST/mirror/v1/contactsHTTP/1.1Authorization:Bearer{authtoken}Content-Type:application/jsonContent-Length:{"id": yName":"HaroldPenguin","iconUrl":""priority":}hasbeeninsertedbyyourservice,yourusermustenableitatMyGlass.)注:PNG640×360像素,透明背景。(NoteForbestresults,useaPNGiconimagethatis640by360pixelswithatransparentbackground.)ID与的凭 OAuth2.0 谷歌镜API的请求必须被使用OAuth2.0认证。您应该使用服务器端的流量,当你的应用程序需要谷歌的API代表的用户,例如当用户处于脱机。这种方法需要从你的客户通过一次性代码到您的服务器,用于获取为您的服务器的和刷新令牌。(RequeststotheMirrorAPImustbeauthorizedusingOAuth2.0credentials.Youshoulduseserver-sideflowwhenyourapplicationneedstoaccessAPIsonbehalfoftheusersuchaswhentheuserisoffline.Thisapproachrequirespassingaone-timeauthorizationcodefromyourtoyourserverthatisusedtoacquireanaccessandrefreshtokensforyour创建一个客户端ID客户端密钥(CreateaIDandsecret)首先,你需要激活谷歌镜为您的应用程序的APIAPIAPI控制台。(First,youneedtoactivatetheMirrorAPIforyourapp.YoucandothisforyourAPIprojectintheAPIsConsole.)在谷歌的API控制台创建一个API项目。(CreateanAPIprojectintheAPIs在你的API项目中选择“服务“选项卡,并启用谷歌镜API。(SelecttheServicestabinyourAPIproject,andenablethe MirrorAPI.)选择在你的API项目的 “选项卡,并单击”创建的OAuth2.0的客户端ID(SelecttheAPIAccesstabinyourAPIproject,andclickCreateanOAuth2.0在品牌信息部分中,为您的应用提供一个名称(如“我的玻璃服务”),然后单击下一步“。提品标识是可选的。(IntheBrandingInformationsection,provideanameforyourapplication(e.g."MyGlassservice"),andclickNext.Providingaproductlogois在客户端ID设置部分,做到以下几点:(IntheIDSettingssection,dotheWeb应用程序的应用程序类型。(SelectWebapplicationfortheApplication点击选项旁边的标题,你的或主机名。(Clickthemoreoptionslinknexttotheheading,Yoursiteorhostname.)列出你的主机在重定向的URI和JavaScript的领域。(ListyourhostnameintheAuthorizedRedirectURIsandJavaScriptoriginsfields.)单击“创建客户端ID。(ClickCreate在的API页面,找到部分的Web应用程序的客户端ID,并注意客户端ID和客户端密钥值。(IntheAPIAccesspage,locatethesectionIDforWebapplicationsandnotetheIDand请求处理(Handlingauthorization用程序的客户端ID改变或已经改变了所要求的范围。(Whenauserloadsyourapplicationforthefirsttime,theyarepresentedwithadialogtograntpermissionforyourapplicationtoaccesstheirGlassaccountwiththerequestedpermissionscopes.Afterthisinitialauthorization,theuserisonlypresentedwiththepermissiondialogifyourapp'sIDchangesortherequestedscopeshavechanged.)验证用户的(Authenticatethe这个初始登录返回结果对象,它包含一个码,如果成功的。(Thisinitialsign-inreturnsanauthorizationresultobjectthatcontainsanauthorizationcodeif交换一个令牌的码(Exchangetheauthorizationcodeforanaccesstoken)码是,您的服务器可以换取一个令牌。此令牌传递给谷歌镜API,您的应用程序用户的数据在有限的时间内授予。(Theauthorizationcodeisaone-timecodethatyourservercanexchangeforanaccesstoken.ThisaccesstokenispassedtotheMirrorAPItograntyourapplicationaccesstouserdataforalimitedtime.)(通常在一个数据库服务器上)。(Ifyourapplicationrequiresofflineaccess,thefirsttimeyourappexchangestheauthorizationcode,italsoreceivesarefreshtokenthatitusestoreceiveanewaccesstokenafteraprevioustokenhasexpired.Yourapplicationstoresthisrefreshtoken(generallyinadatabaseonyourserver)forlateruse.)approval_prompt查询参数设置为强制发送请求。这将导致用户看到一个框,再次给予您的应用程序的权限。(ImportantAlwaysstoreuserrefreshtokens.Ifyourapplicationneedsanewrefreshtokenitmustsentarequestwiththeapproval_promptqueryparametersetto.Thiswillcausetheusertoseeadialogtograntpermissiontoyourapplication下面的代码示例演示了离线一个令牌的码交换和的刷新令牌。(Thefollowingcodesamplesdemonstrateexchanginganauthorizationcodeforanaccesstokenwithofflineaccessandstoringtherefreshtoken.) ceSECRETS_LOCATIONvaluewiththelocationof _secrets.jsonfile.Note:FormoreinformationabouttheOAuth2.0package,seeOAuth2import importcom. importcom. importcom. importcom. importcom. importcom. importcom. importcom. import importjava.io.IOException;importjava.util.Arrays;importjava.util.List;//classMyClass//Path _secrets.jsonwhichshouldcontaina such "web": _id": _secret": "auth_uri": "token_uri": privatestaticfinal SECRETS_LOCATION= privatestaticfinalStringREDIRECT_URI="<YOUR_REGISTERED_REDIRECT_URI>";privatestaticfinalList<String>SCOPES=Arrays.asList( private AuthorizationCodeFlowflow=Exceptionthrownwhenanerroroccurredwhileretrievingpublicstaticclass ceptionextendsExceptionprotectedStringConstructa *@paramauthorizationUrlTheauthorizationURLtoredirecttheuserpublicGetCredential ception(StringauthorizationUrl){this.authorizationUrl=authorizationUrl;}SettheauthorizationpublicvoidsetAuthorizationUrl(StringauthorizationUrl){this.authorizationUrl=authorizationUrl;}@returnthepublicStringgetAuthorizationUrl(){returnauthorizationUrl;}}ExceptionthrownwhenacodeexchangehaspublicstaticclassCodeExchangeExceptionextends ceptionConstructa*@paramauthorizationUrlTheauthorizationURLtoredirecttheuserpublicCodeExchangeException(StringauthorizationUrl){}}ExceptionthrownwhennorefreshtokenhasbeenpublicstaticclassNoRefreshTokenExceptionextends ceptionConstructa@paramauthorizationUrlTheauthorizationURLtoredirecttheuserpublicNoRefreshTokenException(StringauthorizationUrl){}}ExceptionthrownwhennouserIDcouldbeprivatestaticclassNoUserIdExceptionextendsException}Retrievedstoredcredentialsfortheprovideduser@paramuserIdUser's@returnStoredCredentialiffound,{@codenull}staticCredentialgetStoredCredentials(StringuserId)//TODO:Implementthismethodtoworkwithyourdatabase.Instantiatea//CredentialinstancewithstoredaccessTokenandrefreshToken.thrownewUnsupportedOperationException();}StoreOAuth2.0credentialsintheapplication's@paramuserIdUser's@paramcredentialsTheOAuth2.0credentialstostaticvoidstoreCredentials(StringuserId,Credentialcredentials)//TODO:Implementthismethodtoworkwithyour//Storethecredentials.getAccessToken()and//stringvaluesinyourthrownew}Buildanauthorizationflowandstoreitasastaticclass @throwsIOExceptionUnableto AuthorizationCodeFlowgetFlow()throwsIOException{if(flow==null){HttpTransporthttpTransport=newNetHttpTransport();JacksonFactoryjsonFactory=newJacksonFactory(); Secrets= flow AuthorizationCodeFlow.Builder(httpTransport,jsonFactory, }return}ExchangeanauthorizationcodeforOAuth2.0@paramauthorizationCodeAuthorizationcodetoexchangeforOAuth@returnOAuth2.0@throwsCodeExchangeExceptionAnerrorstaticCredentialexchangeCode(StringauthorizationCode)throwsCodeExchangeException{tryAuthorizationCodeFlowflow=getFlow();TokenResponseresponse=returnflow.createAndStoreCredential(response,null);}catch(IOExceptione){System.err.println("Anerroroccurred:"+e);thrownewCodeExchangeException(null);}}SendarequesttotheUserInfoAPItoretrievetheuser's@paramcredentialsOAuth2.0credentialstoauthorizethe@returnUser's@throwsNoUserIdExceptionAnerrorstaticUserinfogetUserInfo(Credentialcredentials)throwsNoUserIdException{Oauth2userInfoServicenewOauth2.Builder(newNetHttpTransport(),newJacksonFactory(),credentials).build();UserinfouserInfo=null;tryuserInfo=}catch(IOExceptione){System.err.println("Anerroroccurred:"+e);}if(userInfo!=null&&userInfo.getId()!=null){returnuserInfo;}elsethrownew}}Retrievetheauthorization@paramuserId @paramstateStatefortheauthorization@returnAuthorizationURLtoredirecttheuser@throwsIOExceptionUnableto publicstaticStringgetAuthorizationUrl(StringuserId,Stringstate)throwsIOException{AuthorizationCodeRequestUrlurlBuilder=getFlow()newAuthorizationUrl().setRedirectUri(REDIRECT_URI).setState(state);urlBuilder.set("user_id",userId);return}RetrievecredentialsusingtheprovidedauthorizationThisfunctionexchangestheauthorizationcodeforanaccesstokenqueriestheUserInfoAPItoretrievethe ID.Ifrefreshtokenhasbeenretrievedalongwithanaccesstoken,itisintheapplicationdatabaseusingthe IDaskey.Ifrefreshtokenhasbeenretrieved,thefunctionchecksinthedatabaseforoneandreturnsitiffoundorthrowsawiththeauthorizationURLtoredirecttheuser@paramauthorizationCodeAuthorizationcodetousetoretrievean@paramstateStatetosettotheauthorizationURLincaseof@returnOAuth2.0credentialsinstancecontaininganaccessand@throwsNoRefreshTokenExceptionNorefreshtokencouldberetrievedtheavailable@throwsIOExceptionUnableto publicstaticCredentialgetCredentials(StringauthorizationCode,Stringstate)throwsCodeExchangeException,NoRefreshTokenException,IOException{StringuserId="";try{Credentialcredentials=exchangeCode(authorizationCode);UserinfouserInfo=getUserInfo(credentials);userId=if(credentials.getRefreshToken()!=null){storeCredentials(userId,credentials);returncredentials;}elsecredentials=if(credentials!=null&&credentials.getRefreshToken()!=null){returncredentials;}}}catch(CodeExchangeExceptione){//Glassservicesshouldtrytoretrievetheuserandcredentialsforthe////Ifnoneisavailable,redirecttheusertotheauthorizationURL.e.setAuthorizationUrl(getAuthorizationUrl(userId,state));throw}catch(NoUserIdExceptione){}//NorefreshtokenhasbeenStringauthorizationUrl=getAuthorizationUrl(userId,throwthrownew}}还有Python、PHP、.NET、Ruby代码与的凭据(Authorizingwithstored用户请求。(Whenusersvisityourappafterasuccessfulfirst-timeauthorizationflow,yourapplicationcanuseastoredrefreshtokentoauthorizerequestswithoutpromptingtheenduser.)如果您已经通过验证的用户,您的应用程序可以retrive刷新令牌从它的数据库中,并在服动。(Ifyouhavealreadyauthenticatedtheuser,yourapplicationcanretrivetherefreshtokenfromitsdatabaseandstorethetokeninaserver-sidesession.Iftherefreshtokenisrevokedorisotherwiseinvalid,you'llneedtocatchthisandtakeappropriateaction.)使用OAuth2.0据(UsingOAuth2.0一旦已检索的OAuth2.0认证前一节中所示,它们可以被用来谷歌镜API服务对象,并发送请求的API。(OnceOAuth2.0credentialshavebeenretrievedasshownintheprevioussection,theycanbeusedtoauthorizeaMirrorAPIserviceobjectandsendrequeststotheAPI.) 镜API服务的对象,并发送一个请求到谷歌镜API来检索一个时间轴项目的元数据。(ThefollowingcodesnippetsshowhowtoinstantiateandauthorizeaMirrorAPIserviceobjectandsendarequesttotheMirrorAPItoretrieveatimelineitem'smetadata.)实例化一个服务对象(Instantiateaservice此代码示例演示如何实例化一个服务对象,然后进行来进行API请求。(ThiscodesampleshowshowtoinstantiateaserviceobjectandthenauthorizeittomakeAPI的Javaimportimport.importcom.importimportimport//.api.servicespublicclassMyClass//BuildaMirrorservice*@paramcredentialsOAuth2.0@returnMirrorservicestaticMirrorbuildService( Credentialcredentials){HttpTransporthttpTransport=newNetHttpTransport();JacksonFactoryjsonFactory=newJacksonFactory();returnnewMirror.Builder(httpTransport,jsonFactory,}//}发送请求,并检查撤销的凭据(Sendauthorizedrequestsandcheckforrevokedcredentials)下面的代码片段使用谷歌的镜子API服务实例,并发送一个,以谷歌镜API的GET请(ThefollowingcodesnippetusesanauthorizedMirrorAPIserviceinstanceandsendsanauthorizedGETrequesttotheMirrorAPItoretrieveatimelineitem'smetadata)如果发生错误,应由的URL将用户重定向到一个HTTP401状态代码,代码检查。谷歌镜APIAPI参考。(Ifanerroroccurs,thecodechecksforanHTTP401statuscode,whichshouldbehandledbyredirectingtheusertotheauthorization谷歌镜API操作都记录在API参考。(MoreMirrorAPIoperationsedintheAPI的importimportimportimportimport.api.services.api.servicesmirrorimport//publicclassMyClass//Printatimelineitem's*@paramserviceMirrorservice@paramitemIdIDofthetimelineitemtoprintmetadatastaticvoidprintTimelineItem(Mirrorservice,StringitemId){try{TimelineItemitem=System.out.println("Text:"+item.getText());System.out.println("HTML:"+item.getHtml());}catch(HttpResponseExceptione){if(e.getStatusCode()==401){//Credentialshavebeen//TODO:RedirecttheusertotheauthorizationURL removethecredentialsfromthedatabase.thrownewUnsupportedOperationException();}}catch(IOExceptione){System.out.println("Anerroroccurred:"+e);}}////} 有关可用的API方法在API参考,并检查一些工作代码,您可以查看我们的终端到终端的示例应用程序。YoucanlearnmoreaboutavailableAPImethodsintheAPIReference,andyoucanreviewourend-to-endExampleAppstoexaminesomeworkingcode.关于上传(AboutMedia谷歌镜API允许您创建一个新的时间表项目时插入附件。(TheMirrorAPIallowsyoutoinsertanattaentwhencreatinganewtimelineitem.)上传选项(Upload谷歌镜API允许传某些类型的二进制数据,或。指定的参考页上的数据,你可以上传任何上传的方法,支持的具体特点:(TheMirrorAPIallowsyoutouploadcertaintypesofbinarydataormediaThespecificcharacteristicsofthedatayoucanuploadarespecifiedonthereferencepageforanymethodthatsupportsmediauploads:)最大上传文件大小:你可以用这种方法的最大数据量(umuploadfilesize: umamountofdatayoucanstorewiththismethod.)接受了的MIME类型:使用这种方法可以二进制数据的类型(AcceptedmediaMIMEtypes:Thetypesofbinarydatayoucanstoreusingthismethod.)有三种不同的方式,使上传请求,你指定你的方法用uploadType请求参数:(Therearethreedifferentwaystomakeuploadrequests,andyouspecify
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 2025至2030年中国全自动刮板式过滤器数据监测研究报告
- 人工智能在病理学诊断的价值
- 办公效率提升的大数据决策支持系统研究
- 办公区域实施医养服务的经济价值探索
- 从商业角度解读传统手工艺与现代产品设计的结合
- 垫资承建工程合同协议
- 垫资合伙合同协议
- 工程劳务管理合同协议
- 处理旧设备购销合同协议
- 地板木龙骨采购合同协议
- 初一泛读黑布林 《霍利的新朋友》
- 粉笔国考行测模考大赛第十季
- 老年综合评估和老年综合征PPT通用通用课件
- 超星尔雅学习通《人力资源招聘与选拔》章节测试含答案
- 路面级配砂砾石垫层施工总结报告
- 主提升机司机培训课件
- 变压器容量计算表
- 连续油管作业技术(共122页).ppt
- 互联网大学生创新创业大赛培训
- 3号钢筋加工场桁吊安装方案
- 部编版(统编)六年级语文下册文学常识及文化常识(共4页)
评论
0/150
提交评论