2018/05/03

利用Google Book API查詢ISBN取得書籍資料(CHT)





最近在【Google Book APIを使ってISBNコードから書籍情報を取得する】有提到利用 Google Book API 查詢 ISBN 並取回結果,操作方式還相當簡單。


接下來有兩個問題:
  • Google Book API 有沒有限制?
  • 舊版 Delphi 和 Starter 版是否可以支援?

首先來看看 Google 怎麼說的

Note: Performing a search does not require authentication, so you do not have to provide the Authorization HTTP header with the GET request. However, if the call is made with authentication, each Volume will include user-specific information, such as purchased status.

範例所用到的 API 是相對沒有限制的,所以可以安心使用。

再來是範例程式碼,它使用的是 FMX,VCL使用上也很接近。

以下是實作程式碼:

procedure TForm1.ParseISBNJSON(AJSON: string);
var
  BookInfo: TJSONObject;
  BookItems: TJsonArray;
  Authors: TJSONArray;
  ThumbnailURL: string;
  ItemCount: Integer;
  I: Integer;
  ImageStream: TMemoryStream;
  LJpg: TJPEGImage;
begin
  BookInfo := TJSONObject.ParseJSONValue(TEncoding.UTF8.GetBytes(AJSON), 0) as TJSONObject;

  Edit2.Text := '';
  Edit3.Text := '';
  Memo1.Text := '';
  Edit4.Text := '';
  Image1.Picture.Assign(nil);

  ItemCount := BookInfo.Get('totalItems').JsonValue.AsJsonNumber.AsInt;
  if ItemCount > 0 then
  begin
    BookItems := BookInfo.Get('items').JsonValue.AsJsonArray;
    with BookItems.Items[0] do
    begin
      Edit2.Text := AsJsonObject.Get('volumeInfo').JsonValue. 
        AsJsonObject.Get('title').JsonValue.Value;
      Edit3.Text := AsJsonObject.Get('volumeInfo').JsonValue. 
        AsJsonObject.Get('subtitle').JsonValue.Value;
      Authors := AsJsonObject.Get('volumeInfo').JsonValue. 
        AsJsonObject.Get('authors').JsonValue.AsJsonArray;
      for I := 0 to Authors.Count - 1 do
      begin
        Memo1.Lines.Add(Authors.Items[i].Value);
      end;

      Edit4.Text := AsJsonObject.Get('volumeInfo').JsonValue.AsJsonObject.
        Get('publishedDate').JsonValue.Value;

      ThumbnailURL := AsJsonObject.Get('volumeInfo').JsonValue.AsJsonObject.
 Get('imageLinks').JsonValue.AsJsonObject.Get('thumbnail').JsonValue.Value;
      LJpg := TJPEGImage.Create;
      ImageStream := TMemoryStream.Create;
      IdHTTP1.Get(ThumbnailURL, ImageStream);
      ImageStream.Position := 0;
      LJpg.LoadFromStream(ImageStream);
      Image1.Picture.Assign(LJpg);
      ImageStream.Free;
      LJpg.Free;
    end;
  end;
end;


可以看出解析語法非常平易近人,在 Starter 版也可以樂勝,又學到一招了。讚!






See also:
Google Book APIを使ってISBNコードから書籍情報を取得する
Google Book APIs: Working with volumes

沒有留言:

張貼留言