How to use the Ubuntu Online Account API to create a Weibo app

Source: Internet
Author: User
Tags i18n

In this article, we will use the online account API provided by the Ubuntu SDK to access the Weibo API and display what is needed. The focus of this article is to show how to use the Online account API. We finally display the following screen:




More information on application development can be found at address: https://developer.ubuntu.com/zh-cn/apps/qml/


1) Create a basic application
We still use our Ubuntu SDK as before to create a basic Weibo QML application.






This allows us to create a basic Weibo QML application. You can use the hotkey Ctrl + R to run it though it's not going to do anything.

2) files required to join the online account
We can refer to the article for a deeper understanding of the online account API. To be able to access, you need to create the following files:
1) weibo.application
Its specific content is as follows:
<?xml version= "1.0" encoding= "UTF-8"?><application> <description>weibo qml</description  >  <desktop-entry>weibo.ubuntu_weibo.desktop</desktop-entry>  <services>    < Service id= "Qml-weibo.ubuntu_qmlweibo" >      <description>watch your favorite Weibo messages</ description>    </service>  </services></application>

2) Weibo.service
The specific content of this is:
<?xml version= "1.0" encoding= "UTF-8"?><service>  <type>sharing</type>  <name >weibo qml</name>  <icon>qml-weibo.png</icon>  <provider>qml-weibo.ubuntu_ Plugin</provider>  <translations>unity-scope-weibo</translations></service>

3) Create a directory of plugin files and create them under itA) main.qml, the contents of which are:
Import Ubuntu.OnlineAccounts.Plugin 1.0OAuthMain {}

b) Qml-weibo.ubuntu_plugin.provider, the contents of which are:
<?xml version= "1.0" encoding= "UTF-8"?><provider> <name>Weibo</name> <icon>weibo/ Icon.png</icon> <translations>unity-scope-weibo</translations> <plugin>generic-oauth< /plugin> <domains>.*weibo\.com</domains> <single-account>true</single-account> < template> <group name= "auth" > <setting name= "method" >oauth2</setting> <setting name= "          Mechanism ">web_server</setting> <group name=" Oauth2 "> <group name=" Web_server "> <setting name= "Host" >api.weibo.com</setting> <setting name= "Authpath" >oauth2/authorize</sett ing> <setting name= "Tokenpath" >oauth2/access_token</setting> <setting name= "Redirectur I ">https://api.weibo.com/oauth2/default.html</setting> <setting name=" Responsetype ">code</sett ing> <setting name= "ClientId" >your Developer Key</setting> <setting type= "as" name= "allowedschemes" >[' https ', ' http ']</setting> <setting name= "Clientsecret" >your developer secret</setting> <setting name= "Forceclientauth Viarequestbody "type=" B ">true</setting> </group> </group> </group> </template& Gt;</provider>

In the above file, be sure to enter your own " Your Developer Keyand Your developer Secret”。 This you need to apply on the Weibo API's website. The schema for the entire file is:



4) Modify the Manifest.json file as follows
{    "name": "Qml-weibo.ubuntu",    "description": "Description of Qml-weibo",    "architecture": "All",    " Title ":" Qml-weibo ","    hooks ": {        " Qmlweibo ": {            " account-application ":" Weibo.application ",            " Account-service ":" Weibo.service ",            " AppArmor ":" Qmlweibo.apparmor ",            " desktop ":" Qmlweibo.desktop "        },        "Plugin": {            "Account-provider": "Plugin/qml-weibo.ubuntu_plugin.provider",            "Account-qml-plugin": "Plugin/qml"        }    ,    "version": "0.1",    "maintainer": "Xiaoguo, Liu <[email protected]>",    "framework": "Ubuntu-sdk-14.10"}


Some settings for account and plugin are added here.

5) in order for the. Service,.application and. provider files to be displayed properly, we add the following to the "Qml-weibo.qmlproject"
    Files {        filter: "*.service"    }    Files {        filter: "*.application"    }    Files {        filter: "*. Provider "    }


Here, we have basically modified or added the files we need.

3) Design the UI of the application we will modify our MAIN.QML file. We used a column layout manager to manage our controls.
    • Use a ListView (Accountslist) to display all of our relevant accounts. This can be seen in "system settings" in the "account"

    • Use a button called "createaccountbtn" to create a Weibo online account
    • Use a different listview (Weibolist) list to display the content of Weibo

Import QtQuick 2.0import ubuntu.components 0.1import Ubuntu.Components.ListItems 0.1 as Listitemimport Ubuntu.onlineaccounts 0.1import Ubuntu.OnlineAccounts.Client 0.1import "Weiboapi.js" as Apimainview {id:main//OB Jectname for functional testing purposes (AUTOPILOT-QT5) ObjectName: "MainView"//note! ApplicationName needs to match the "name" field of the click Manifest ApplicationName: "Qml-weibo.ubuntu"/* Thi S property enables the application to change orientation when the device is rotated.    The default is False. *///automaticorientation:true Property string Accesstoken: "" Width:units.gu (+) Height:units.gu (+) Pa            GE {id:root clip:true title:i18n.tr ("Weibo") Column {Spacing:units.gu (2) Width:parent.width ListView {id:accountslist anchors.horizontalcenter:p Arent. Center anchors.verticalCenter:parent.             Center   Height:contentheight width:root.width spacing:units.gu (1) Model:accoun                    Tsmodel Delegate:rectangle {id:wrapper width:accountsList.width Height:units.gu (Ten) color:accts.enabled? "Green": "Red" Accountservice {id:accts objecthandle: Accountservicehandle onauthenticated: {console.log ("Reply:" + json.str                            Ingify (reply));                            var obj = json.parse (json.stringify (reply)); Console.log ("Accesstoken:" + obj.)                            Accesstoken); Main.accesstoken = obj.                            Accesstoken;                            Make the Authenticate button invisile accountslist.visible = false; Start to get the data APi.getstatus (); } onauthenticationerror: {Console.log ("Authentication failed, code" + Error.code) Authenticatebtn.text = displayName + "Error" + Error.code + "Please do it Again"                        ; }} Button {id:authenticatebtn ancho Rs.fill:parent Anchors.margins:units.gu (2) text:i18n.tr ("Authenticate%1" ). Arg (Model.displayname + "" + model.providername) onclicked: {var par                AMS = {} accts.authenticate (params)}} }} Button {id:createaccountbtn anchors.horizontalcenter:parent.h Orizontalcenter Width:parent.width Height:units.gu(8) text:i18n.tr ("Request access") OnClicked:setup.exec ()} Listmode l {Id:modelweibo} ListView {id:weibolist Width:pa                Rent.width height:parent.height spacing:units.gu (1) Model:modelweibo                    Delegate:rectangle {width:parent.width Height:units.gu (8)  Color: "Lightgrey" Borderimage {id:image Source: {return Json.parse (' + json.stringify (user) + '). Profile_image_url} width:parent.height; Height:parent.height Border.left:5; Border.top:5 Border.right:5; Border.bottom:5} Text {Id:text x:                     Image.width + 10   width:parent.width-image.width-20 height:parent.height text: {retur N Json.parse (' + json.stringify (user) + '). Name}}}}} Ac Countservicemodel {Id:accountsmodel ApplicationID: "Qml-weibo.ubuntu_qmlweibo"} Setup {ID:            Setup ProviderID: "Qml-weibo.ubuntu_plugin" ApplicationID: "Qml-weibo.ubuntu_qmlweibo" onfinished: {        Createaccountbtn.visible = false; }} component.oncompleted: {if (Accountsmodel.count = = 0) {//If there is no such a account,        We need to create such one setup.setup.exec (); } else {//Hide the button since the account had already been created createaccountbtn.visible = f Alse}}}


We have designed weiboapi.js files to help us get the specific content of Weibo:
Weibo//home Statusfunction weibohomestatus (token, page, observer) {var url = "Https://api.weibo.com/2/statuses/home_timeline.json    Access_token= "+ token +" &page= "+ page Console.log (" Home status Start ... ") console.log (" url: "+ URL);    var doc = new XMLHttpRequest (); Doc.onreadystatechange = function () {if (doc.readystate = = xmlhttprequest.headers_received) {C            Onsole.log ("Home status in Progress ...");                    } else if (doc.readystate = = Xmlhttprequest.done) {if (doc.status! = 200) { Console.log ("!!!                    Network Connection failed! ")  Observer.update ("error", Doc.status)} else {Console.log ("--Home status                    Succeeded! ");    if (Doc.responsetext = = null) {observer.update ("null", Doc.status)                } else {//Console.log ("Home Status:done" + doc.responsetext)                        Console.log ("Some data received!")                        var json = json.parse (' + doc.responsetext+ ');                    Observer.update ("Fine", JSON);    }}}} doc.open ("GET", url, True);    Doc.setrequestheader ("Content-type", "Application/json"); Doc.send ();} function GetStatus () {///We can get some data from the web and display them console.log ("going to get some data fro M Web ") function observer () {} Observer.prototype = {update:function (status, result) {Co            Nsole.log ("Got updated!"); if (Status! = "Error") {if (result.error) {Console.log ("Result.error:" + result.error)                ;                    }else {console.log ("Got updated1!"); for (var i = 0; i < Result.stAtuses.length; i++) {modelweibo.append (Result.statuses[i])}}}el            se{Console.log ("Something is wrong!"); }}} weibohomestatus (Main.accesstoken, 1, New Observer ());}

The source of the entire application in the address
git clone https://gitcafe.com/ubuntu/weiboqml.git

How to use the Ubuntu Online Account API to create a Weibo app

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.