首页 > 代码库 > 怎样用Google APIs和Google的应用系统进行集成(3)----调用Google 发现(Discovery)API的RESTful服务

怎样用Google APIs和Google的应用系统进行集成(3)----调用Google 发现(Discovery)API的RESTful服务

说了这么多,那么首先同意我以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;
	}
	@Override
	public 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是谷歌官方提供的解析JSON数据:
1.谷歌GSON这个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源码。