如何用Google APIs和Google的應用系統進行整合(3)----調用Google Discovery RESTful服務

來源:互聯網
上載者:User

標籤:google apis restful服   調用restful   gson   java   http   

說了這麼多,那麼首先允許我以Google Discovery RESTful服務為例,給大家示範如何用最普通的Java代碼調用Google Discovery RESTful服務。

引言:

在“如何用Google APIs和Google的應用系統進行整合(2)”的下面,我列出了當前Google APIs支援的所有的Google APIs。其實這個表格是我用代碼調用Google Discovery RESTFul服務自動產生的。具體的步驟和代碼如下:

(1) 訪問Google Discovery RESTFul的服務:https://www.googleapis.com/discovery/v1/apis 可以獲得RESTFul服務返回的結果:通過訪問 JSONtoStringConverter-->readJSONSAsString()

package com.henry.json.gson.googlediscovery;import java.io.ByteArrayOutputStream;import java.io.IOException;import java.io.InputStream;import java.net.HttpURLConnection;import java.net.MalformedURLException;import java.net.URL;public class JSONtoStringConverter {   private String url_path="https://www.googleapis.com/discovery/v1/apis";public String readJSONSAsString(){InputStream in=this.getJSONSchemaInputStream();return readJSONSAsString(in);}private InputStream getJSONSchemaInputStream() {InputStream ipStream = null;if (url_path == null) {throw new IllegalArgumentException("The URL Path can't be empty!!!");}try {URL url = new URL(url_path);HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();httpConnection.setRequestMethod("GET");httpConnection.setReadTimeout(30000);httpConnection.setDoInput(true);ipStream = httpConnection.getInputStream();} catch (MalformedURLException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}return ipStream;}private String readJSONSAsString(InputStream in){String jsonString="";ByteArrayOutputStream baosArrayOutputStream=new ByteArrayOutputStream();byte[] bytes=new byte[1024];int len=0;try {while((len=in.read(bytes))!=-1){baosArrayOutputStream.write(bytes, 0, len);}jsonString=new String(baosArrayOutputStream.toByteArray(),"utf-8");} catch (IOException e) {e.printStackTrace();}System.out.println(jsonString);return jsonString;}public static void main(String[] args) {JSONtoStringConverter jSONtoStringConverter=new JSONtoStringConverter();jSONtoStringConverter.readJSONSAsString();}}

(2) 解析返回的JSON資料,但是解析以前,我們需要建立相應的JavaBean,這樣就能把JSON的對象和Java的對象映射起來。

2.1 GoogleDiscoveryBean

package com.henry.json.gson.googlediscovery;import java.util.List;public class GoogleDiscoveryBean {private String kind;private String discoveryVersion;private List<Items> items;public String getKind() {return kind;}public void setKind(String kind) {this.kind = kind;}public String getDiscoveryVersion() {return discoveryVersion;}public void setDiscoveryVersion(String discoveryVersion) {this.discoveryVersion = discoveryVersion;}public List<Items> getItems() {return items;}public void setItems(List<Items> items) {this.items = items;}@Overridepublic String toString(){return kind+"--"+discoveryVersion+"--size:"+items.size();}}

2.2  Items

package com.henry.json.gson.googlediscovery;/*"kind": "discovery#directoryItem","id": "adexchangebuyer:v1","name": "adexchangebuyer","version": "v1","title": "Ad Exchange Buyer API","description": "Lets you manage your Ad Exchange Buyer account.","discoveryRestUrl": "https://www.googleapis.com/discovery/v1/apis/adexchangebuyer/v1/rest","discoveryLink": "./apis/adexchangebuyer/v1/rest","icons": { "x16": "http://www.google.com/images/icons/product/doubleclick-16.gif", "x32": "http://www.google.com/images/icons/product/doubleclick-32.gif"},"documentationLink": "https://developers.google.com/ad-exchange/buyer-rest","preferred": false*/public class Items { private String kind; private String id; private String name; private String version; private String title; private String description; private String discoveryRestUrl; private String discoveryLink; private String documentationLink; private String preferred;public String getKind() {return kind;}public void setKind(String kind) {this.kind = kind;}public String getId() {return id;}public void setId(String id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public String getVersion() {return version;}public void setVersion(String version) {this.version = version;}public String getTitle() {return title;}public void setTitle(String title) {this.title = title;}public String getDescription() {return description;}public void setDescription(String description) {this.description = description;}public String getDiscoveryRestUrl() {return discoveryRestUrl;}public void setDiscoveryRestUrl(String discoveryRestUrl) {this.discoveryRestUrl = discoveryRestUrl;}public String getDiscoveryLink() {return discoveryLink;}public void setDiscoveryLink(String discoveryLink) {this.discoveryLink = discoveryLink;}public String getDocumentationLink() {return documentationLink;}public void setDocumentationLink(String documentationLink) {this.documentationLink = documentationLink;}public String getPreferred() {return preferred;}public void setPreferred(String preferred) {this.preferred = preferred;}}

(3) 下載JSON java的庫: http://code.google.com/p/google-gson/  
GSon是Google官方提供的解析JSON資料:
1.GoogleGSON這個Java類庫可以把Java對象轉換成JSON,也可以把JSON字串轉換成一個相等的Java對象。
2.Gson支援任意複雜Java對象包括沒有原始碼的對象。

(4) 建立一個GoogleGSonTools: 這個類會把Google Discovery RESTful服務返回的JSON的字串,自動轉換成GoogleDiscoveryBean對象,這個方法不到10行,就這麼簡單。

package com.henry.json.gson.googlediscovery;import com.google.gson.Gson;public class GoogleGSonTools {public static <T> T getGoogleDiscoveryBean(String josnString, Class<T> clazz) {T t = null;try {Gson gson = new Gson();t = gson.fromJson(josnString, clazz);} catch (Exception e) {}return t;}}

(5)結合上面的(1)~(4),我們把其返回的值,格式化成一個HTML的表格。

package com.henry.json.gson.googlediscovery;import java.util.List;public class GoogleAPIsListViewService {  public String listAllGoogleAPIs(){    StringBuilder sbBuilder=new StringBuilder("<table border=\"1\" style=\"word-break:break-all; word-wrap:break-word;\"> <tr><td>序號</td><td>API 標題</td><td>名字</td><td>版本</td><td>RestFul請求的URL</td><td>RestFul請求的URL</td></tr>");JSONtoStringConverter jSONtoStringConverter=new JSONtoStringConverter();String json=jSONtoStringConverter.readJSONSAsString();GoogleDiscoveryBean googleDiscoveryBean=GoogleGSonTools.getGoogleDiscoveryBean(json, GoogleDiscoveryBean.class);List<Items> listItems=googleDiscoveryBean.getItems();if(listItems!=null&&listItems.size()>0){for(int i=0;i<listItems.size();i++){  Items items=listItems.get(i);  sbBuilder.append("<tr>");  sbBuilder.append("<td>").append(" "+(i+1)+" ").append("</td>");  sbBuilder.append("<td>").append(items.getTitle()).append("</td>");  sbBuilder.append("<td>").append(items.getName()).append("</td>");  sbBuilder.append("<td>").append(items.getVersion()).append("</td>");  sbBuilder.append("<td>").append(items.getDiscoveryRestUrl()).append("</td>");  sbBuilder.append("<td>").append(items.getDocumentationLink()).append("</td>");  sbBuilder.append("</tr>");}}sbBuilder.append("</table>");System.out.println(sbBuilder.toString());return sbBuilder.toString();}public static void main(String[] args) {GoogleAPIsListViewService gavs=new GoogleAPIsListViewService();gavs.listAllGoogleAPIs();}}

輸出的結果就是,就是“如何用Google APIs和Google的應用系統進行整合(2)”文章中看到的表格的html原始碼。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.