Google base的介紹、原理分析與應用實例

    這幾天使用Google base發佈了一些東西,感受用起來很方便並且頗有用,關於這方面的博客如今基本尚未,這裏就給你們介紹一下Gbase的原理與使用。
    Gbase是一個幫助你發表虛擬類型的任何信息的免費服務,用戶把信息發佈到Gbase上,而後能夠在google網站上搜索。這個服務就頗有用,咱們知道google 的搜索能力很強大,若是咱們把咱們的產品或者服務發佈到Gbase上,就有可能讓全世界的人看到咱們發佈的信息。
    發佈一個項目很簡單,前提是必須得有一個google賬戶,有帳戶的用戶步驟以下:
    1.進入google base網站首頁:http://www.google.com/base/
    2.點擊「One at a time」,就進入了添加item頁面,或者直接登陸進去本身的Gbase首頁,點擊左下角「Add a item」按鈕就能夠添加item。
    3.填完信息後,點擊「Publish」便可。
    這裏添加的信息包括item類別(你能夠選擇已有的類別,或者自定義一個類別),而後填寫可能包含的數量、金額和描述信息等等。上述方法是一次添加一個item的方式,若是你想批量添加,能夠添加一個本地的xml文件,該文件符合google base規定的格式。

    下面介紹如何使用Google base API編寫Gbase應用,主要是給程序開發等編程人員提供參考。
    Data item:在Google base 中描述一個單獨的entry,他包含一組屬性。
    Attribute:描述內容的name/pair對,如 <g:label>kung pao chicken</g:label>
    一個entry的信息以下所示:
<? xml version ='1.0' ?>
< entry xmlns ='http://www.w3.org/2005/Atom'
         xmlns:g ='http://base.google.com/ns/1.0' >
         < author >
             < name >Jane Doe </ name >
             < email >JaneDoe@gmail.com </ email >
         </ author >
         < category scheme ='http://www.google.com/type' term ='googlebase.item' />
         < title type ='text' >He Jingxian's chicken </ title >
         < content type ='xhtml' >
             < div xmlns ='http://www.w3.org/1999/xhtml' >Delectable Sichuan specialty </ div >
         </ content >
         < link rel ='alternate' type ='text/html' href ='http://www.host.com/123456jsh9' />
         < g:item_type >Recipes </ g:item_type >
         < g:cooking_time >30 </ g:cooking_time >
         < g:main_ingredient >chicken </ g:main_ingredient >
         < g:main_ingredient >chili peppers </ g:main_ingredient >
         < g:main_ingredient >peanuts </ g:main_ingredient >
         < g:spices_used >Szechuan peppercorn </ g:spices_used >
         < g:cook_technique >blackened </ g:cook_technique >
</ entry >

    每個item都有一個URL,或者說一個惟一的ID,用於標識這個item或者說entry,比我添加的一條記錄的URL以下所示:
    http://base.google.com/base/feeds/items/2139682888944988653
    item ID是
2139682888944988653。
    這個URL通常是程序代碼中使用的,item本身生成的URL是http://base.google.com/base/a/6380400/D2139682888944988653,他們的實質都是同樣的。
    每個Googel base API操做跟HTTP方法相同,你可使用HTTP GET、POST、PUT和DELETE方法來操做。
    一個查詢的例子以下所示:

    發送的HTTP請求是:
GET /base/feeds/snippets?bq=digital+camera
Content-Type: application/atom+xml
Authorization: AuthSub token=""
X-Google-Key: key=ABQIAAAA7VerLsOcLuBYXR7vZI2NjhTRERdeAiwZ9EeJWta3L_JZVS0bOBRIFbhTrQjhHE52fqjZvfabYYyn6A
    因爲響應信息比較多,這裏就不顯示了。

    使用API添加item的代碼以下所示。
InsertExample.java代碼:
/* Copyright (c) 2006 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*         http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/


package cn.edu.xidian;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.StringTokenizer;

/**
*    Add a new item to Google Base using the Google Base data API server.
*/

public class InsertExample {
     /**
     * URL of the authenticated customer feed.
     */

     private static final String ITEMS_FEED = "http://base.google.com/base/feeds/items";

    /**
     * The data item we are going to insert, in XML/Atom format.
     */

    private static final String DATA_ITEM =
                "<?xml version='1.0'?>\n" +
                "<entry xmlns='http://www.w3.org/2005/Atom'\n" +
                "        xmlns:g='http://base.google.com/ns/1.0'>\n" +
                "    <g:item_type type='text'>repaceService</g:item_type>\n" +
                "    <title type='text'>EchoService_ID</title>\n" +
                "    <content type='xhtml'>08d8440b82554bad9a7a5ad9a1487</content>\n" +
                "</entry>";

    /**
     * URL used for authenticating and obtaining an authentication token.
     * More details about how it works:
     * <code>http://code.google.com/apis/accounts/AuthForInstalledApps.html<code>
     */

    private static final String AUTHENTICATION_URL = "https://www.google.com/accounts/ClientLogin";
    
    /**
     * Fill in your Google Account email here.
     */

    private static final String EMAIL = "youremail@gmail.com";
    
    /**
     * Fill in your Google Account password here.
     */

    private static final String PASSWORD = "yourpassword";
    
    /**
     * The main method constructs a <code>InsertExample</code> instance, obtains an
     * authorization token and posts a new item to Google Base.
     */

    public static void main(String[] args) throws MalformedURLException, IOException {
        InsertExample insertExample = new InsertExample();
        String token = insertExample.authenticate();
        System.out.println("Obtained authorization token: " + token);
        insertExample.postItem(token);
    }

    /**
     * Inserts <code>DATA_ITEM</code> by making a POST request to
     * <code>ITEMS_URL<code>.
     * @param token authentication token obtained using <code>authenticate</code>
     * @throws IOException if an I/O exception occurs while creating/writing/
     *                 reading the request
     */

    public void postItem(String token) throws IOException {
        HttpURLConnection connection = (HttpURLConnection)(new URL(ITEMS_FEED)).openConnection();
        
        connection.setDoInput(true);
        connection.setDoOutput(true);
        
        // Set the properties of the connection: the Http method, the content type
        // of the POST request and the authorization header
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/atom+xml");
        connection.setRequestProperty("Authorization", "GoogleLogin auth=" + token);

        // Post the data item
        OutputStream outputStream = connection.getOutputStream();
        outputStream.write(DATA_ITEM.getBytes());
        outputStream.close();
    
        // Retrieve the output
        int responseCode = connection.getResponseCode();
        InputStream inputStream;
        if (responseCode == HttpURLConnection.HTTP_CREATED) {
            inputStream = connection.getInputStream();
        } else {
            inputStream = connection.getErrorStream();
        }
        
        // write the output to the console
        System.out.println(toString(inputStream));
        
    }

    /**
     * Retrieves the authentication token for the provided set of credentials.
     * @return the authorization token that can be used to access authenticated
     *                 Google Base data API feeds
     */

    public String authenticate() {
        // create the login request
        String postOutput = null;
        try {
            URL url = new URL(AUTHENTICATION_URL);
            postOutput = makeLoginRequest(url);
        } catch (IOException e) {
            System.out.println("Could not connect to authentication server: "
                    + e.toString());
            System.exit(1);
        }
    
        // Parse the result of the login request. If everything went fine, the
        // response will look like
        //            HTTP/1.0 200 OK
        //            Server: GFE/1.3
        //            Content-Type: text/plain
        //            SID=DQAAAGgA...7Zg8CTN
        //            LSID=DQAAAGsA...lk8BBbG
        //            Auth=DQAAAGgA...dk3fA5N
        // so all we need to do is look for "Auth" and get the token that comes after it
    
        StringTokenizer tokenizer = new StringTokenizer(postOutput, "=\n ");
        String token = null;
        
        while (tokenizer.hasMoreElements()) {
            if (tokenizer.nextToken().equals("Auth")) {
                if (tokenizer.hasMoreElements()) {
                    token = tokenizer.nextToken();
                }
                break;
            }
        }
        if (token == null) {
            System.out.println("Authentication error. Response from server:\n" + postOutput);
            System.exit(1);
        }
        return token;
    }

    /**
     * Makes a HTTP POST request to the provided {@code url} given the provided
     * {@code parameters}. It returns the output from the POST handler as a
     * String object.
     *
     * @param url the URL to post the request
     * @return the output from the handler
     * @throws IOException if an I/O exception occurs while
     *                     creating/writing/reading the request
     */

    private String makeLoginRequest(URL url)
            throws IOException {
        // Create a login request. A login request is a POST request that looks like
        // POST /accounts/ClientLogin HTTP/1.0
        // Content-type: application/x-www-form-urlencoded
        // Email=johndoe@gmail.com&Passwd=north23AZ&service=gbase&source=Insert Example

        // Open connection
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
    
        
        // Set properties of the connection
        urlConnection.setRequestMethod("POST");
        urlConnection.setDoInput(true);
        urlConnection.setDoOutput(true);
        urlConnection.setUseCaches(false);
        urlConnection.setRequestProperty("Content-Type",
                                                                         "application/x-www-form-urlencoded");
    
        // Form the POST parameters
        StringBuilder content = new StringBuilder();
        content.append("Email=").append(URLEncoder.encode(EMAIL, "UTF-8"));
        content.append("&Passwd=").append(URLEncoder.encode(PASSWORD, "UTF-8"));
        content.append("&source=").append(URLEncoder.encode("Repace service example", "UTF-8"));
        content.append("&service=").append(URLEncoder.encode("gbase", "UTF-8"));

        OutputStream outputStream = urlConnection.getOutputStream();
        outputStream.write(content.toString().getBytes("UTF-8"));
        outputStream.close();
    
        // Retrieve the output
        int responseCode = urlConnection.getResponseCode();
        InputStream inputStream;
        if (responseCode == HttpURLConnection.HTTP_OK) {
            inputStream = urlConnection.getInputStream();
        } else {
            inputStream = urlConnection.getErrorStream();
        }
    
        return toString(inputStream);
    }

    /**
     * Writes the content of the input stream to a <code>String<code>.
     */

    private String toString(InputStream inputStream) throws IOException {
        String string;
        StringBuilder outputBuilder = new StringBuilder();
        if (inputStream != null) {
            BufferedReader reader =
                    new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
            while (null != (string = reader.readLine())) {
                outputBuilder.append(string).append('\n');
            }
        }
        return outputBuilder.toString();
    }
}

    若是email和密碼正確,驗證經過,則在你的email賬號下的Gbase下添加了一條item,這個item須要大概1天的時間可以經過google搜索。
QueryExample3.java代碼:
/* Copyright (c) 2006 Google Inc.                                                                                                                                                                                                                                                                                                                                                                
*                                                                                                                                                                                                                                                                                                                                                                                                                            
* Licensed under the Apache License, Version 2.0 (the "License");                                                                                                                                                                                                                                                                                            
* you may not use this file except in compliance with the License.                                                                                                                                                                                                                                                                                            
* You may obtain a copy of the License at                                                                                                                                                                                                                                                                                                                                            
*                                                                                                                                                                                                                                                                                                                                                                                                                            
*         http://www.apache.org/licenses/LICENSE-2.0                                                                                                                                                                                                                                                                                                                                
*                                                                                                                                                                                                                                                                                                                                                                                                                            
* Unless required by applicable law or agreed to in writing, software                                                                                                                                                                                                                                                                                    
* distributed under the License is distributed on an "AS IS" BASIS,                                                                                                                                                                                                                                                                                        
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.                                                                                                                                                                                                                                                                            
* See the License for the specific language governing permissions and                                                                                                                                                                                                                                                                                    
* limitations under the License.                                                                                                                                                                                                                                                                                                                                                                
*/


package cn.edu.xidian;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.StringTokenizer;

/**
* Display all items of a specific customer.
*/

public class QueryExample3 {
     /**
     * URL of the authenticated customer feed.
     */

     private static final String ITEMS_FEED = "http://base.google.com/base/feeds/items/2139682888944988653";

    /**
     * URL used for authenticating and obtaining an authentication token.
     * More details about how it works:
     * <code>http://code.google.com/apis/accounts/AuthForInstalledApps.html<code>
     */

    private static final String AUTHENTICATION_URL = "https://www.google.com/accounts/ClientLogin";

    /**
     * Fill in your Google Account email here.
     */

    private static final String EMAIL = "youremail@gmail.com";
    
    /**
     * Fill in your Google Account password here.
     */

    private static final String PASSWORD = "yourpassword";
    
    /**
     * Create a <code>QueryExample3</code> instance and call
     * <code>displayMyItems</code>, which displays all items that belong to the
     * currently authenticated user.
     */

    public static void main(String[] args) throws IOException {
        QueryExample3 queryExample = new QueryExample3();
        String token = queryExample.authenticate();
        queryExample.displayMyItems(token);
    }

    /**
     * Retrieves the authentication token for the provided set of credentials.
     * @return the authorization token that can be used to access authenticated
     *                 Google Base data API feeds
     */

    public String authenticate() {
        // create the login request
        String postOutput = null;
        try {
            URL url = new URL(AUTHENTICATION_URL);
            postOutput = makeLoginRequest(url);
        } catch (IOException e) {
            System.out.println("Could not connect to authentication server: "
                    + e.toString());
            System.exit(1);
        }
    
        // Parse the result of the login request. If everything went fine, the
        // response will look like
        //            HTTP/1.0 200 OK
        //            Server: GFE/1.3
        //            Content-Type: text/plain
        //            SID=DQAAAGgA...7Zg8CTN
        //            LSID=DQAAAGsA...lk8BBbG
        //            Auth=DQAAAGgA...dk3fA5N
        // so all we need to do is look for "Auth" and get the token that comes after it
    
        StringTokenizer tokenizer = new StringTokenizer(postOutput, "=\n ");
        String token = null;
        
        while (tokenizer.hasMoreElements()) {
            if (tokenizer.nextToken().equals("Auth")) {
                if (tokenizer.hasMoreElements()) {
                    token = tokenizer.nextToken();
                }
                break;
            }
        }
        if (token == null) {
            System.out.println("Authentication error. Response from server:\n" + postOutput);
            System.exit(1);
        }
        return token;
    }

    /**
     * Displays the "items" feed, that is the feed that contains the items that
     * belong to the currently authenticated user.
     *
     * @param token the authorization token, as returned by
     *                <code>authenticate<code>
     * @throws IOException if an IOException occurs while creating/reading the
     *                 request
     */

    public void displayMyItems(String token) throws MalformedURLException, IOException {
        HttpURLConnection connection = (HttpURLConnection)(new URL(ITEMS_FEED)).openConnection() ;
        // Set properties of the connection
        connection.setRequestMethod("GET");
        connection.setRequestProperty("Authorization", "GoogleLogin auth=" + token);

        int responseCode = connection.getResponseCode();
        InputStream inputStream;
        if (responseCode == HttpURLConnection.HTTP_OK) {
            inputStream = connection.getInputStream();
        } else {
            inputStream = connection.getErrorStream();
        }
        
        System.out.println(toString(inputStream));
     }
    
    /**
     * Makes a HTTP POST request to the provided {@code url} given the provided
     * {@code parameters}. It returns the output from the POST handler as a
     * String object.
     *
     * @param url the URL to post the request
     * @return the output from the Google Accounts server, as string
     * @throws IOException if an I/O exception occurs while
     *                     creating/writing/reading the request
     */

    private String makeLoginRequest(URL url)
            throws IOException {
        // Create a login request. A login request is a POST request that looks like
        // POST /accounts/ClientLogin HTTP/1.0
        // Content-type: application/x-www-form-urlencoded
        // Email=johndoe@gmail.com&Passwd=north23AZ&service=gbase&source=Insert Example

        // Open connection
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
    
        
        // Set properties of the connection
        urlConnection.setRequestMethod("POST");
        urlConnection.setDoInput(true);
        urlConnection.setDoOutput(true);
        urlConnection.setUseCaches(false);
        urlConnection.setRequestProperty("Content-Type",
                                                                         "application/x-www-form-urlencoded");
    
        // Form the POST parameters
        StringBuilder content = new StringBuilder();
        content.append("Email=").append(URLEncoder.encode(EMAIL, "UTF-8"));
        content.append("&Passwd=").append(URLEncoder.encode(PASSWORD, "UTF-8"));
        content.append("&service=").append(URLEncoder.encode("gbase", "UTF-8"));
        content.append("&source=").append(URLEncoder.encode("Repace service example", "UTF-8"));

        OutputStream outputStream = urlConnection.getOutputStream();
        outputStream.write(content.toString().getBytes("UTF-8"));
        outputStream.close();
    
        // Retrieve the output
        int responseCode = urlConnection.getResponseCode();
        InputStream inputStream;
        if (responseCode == HttpURLConnection.HTTP_OK) {
            inputStream = urlConnection.getInputStream();
        } else {
            inputStream = urlConnection.getErrorStream();
        }
    
        return toString(inputStream);
    }

    /**
     * Writes the content of the input stream to a <code>String<code>.
     */

    private String toString(InputStream inputStream) throws IOException {
        String string;
        StringBuilder outputBuilder = new StringBuilder();
        if (inputStream != null) {
            BufferedReader reader =
                    new BufferedReader(new InputStreamReader(inputStream));
            while (null != (string = reader.readLine())) {
                outputBuilder.append(string).append('\n');
            }
        }
        return outputBuilder.toString();
    }
}
   
    改代碼的執行結果以下:
<? xml version ='1.0' encoding ='UTF-8' ?> < entry xmlns ='http://www.w3.org/2005/Atom' xmlns:gm ='http://base.google.com/ns-metadata/1.0' xmlns:g ='http://base.google.com/ns/1.0' xmlns:batch ='http://schemas.google.com/gdata/batch' > < id >http://www.google.com/base/feeds/items/2139682888944988653 </ id > < published >2009-08-01T12:55:09.000Z </ published > < updated >2009-08-01T12:55:09.000Z </ updated > < category scheme ='http://base.google.com/categories/itemtypes' term ='repaceService' /> < title type ='text' >EchoService_ID </ title > < content type ='html' >08d8440b82554bad9a7a5ad9a1487 </ content > < link rel ='alternate' type ='text/html' href ='http://base.google.com/base/a/6380400/D2139682888944988653' /> < link rel ='self' type ='application/atom+xml' href ='http://www.google.com/base/feeds/items/2139682888944988653' /> < link rel ='edit' type ='application/atom+xml' href ='http://www.google.com/base/feeds/items/2139682888944988653' /> < author > < name >Panpan Zhan </ name > < email >anon-tolts2g0m1kt@base.google.com </ email > </ author > < g:target_country type ='text' >US </ g:target_country > < g:expiration_date type ='dateTime' >2038-01-19T03:14:07Z </ g:expiration_date > < g:customer_id type ='int' >6380400 </ g:customer_id > < g:item_language type ='text' >en </ g:item_language > < g:item_type type ='text' >repaceService </ g:item_type > < gd:feedLink xmlns:gd ='http://schemas.google.com/g/2005' rel ='media' href ='http://www.google.com/base/feeds/items/2139682888944988653/media' countHint ='0' /> </ entry >
    這樣就完成了一些簡單的Gbase操做的例子。
相關文章
相關標籤/搜索