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 >[email protected] </ 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 = "[email protected]";
    
    /**
     * 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 protected]&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 = "[email protected]";
    
    /**
     * 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 protected]&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 >[email protected] </ 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操作的例子。

你可能感兴趣的:(Google,职场,base,休闲)