Java AmazonAPIを使って検索したものをとってくる
したいこと
書籍のジャンルの中で、「ペン」と調べた時に出てくる書籍のタイトルを表示させる。
サンプルコード
ItemLookupSample.java
package test; import java.util.HashMap; import java.util.Map; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; public class ItemLookupSample { private static final String AWS_ACCESS_KEY_ID = "アクセスキー"; private static final String AWS_SECRET_KEY = "シークレットキー"; private static final String ASSOCIATE_TAG = ""; private static final String ENDPOINT = "ecs.amazonaws.jp"; public static void main(String[] args) { /* * Set up the signed requests helper */ SignedRequestsHelper helper; try { helper = SignedRequestsHelper.getInstance(ENDPOINT, AWS_ACCESS_KEY_ID, AWS_SECRET_KEY, ASSOCIATE_TAG); } catch (Exception e) { e.printStackTrace(); return; } String requestUrl = null; String title = null; System.out.println("Map form example:"); Map<String, String> params = new HashMap<String, String>(); params.put("Service", "AWSECommerceService"); params.put("Version", "2009-03-31"); params.put("Operation", "ItemSearch"); params.put("ResponseGroup", "Small"); params.put("AssociateTag", ASSOCIATE_TAG); params.put("SearchIndex", "Books"); params.put("Keywords", "ペン"); requestUrl = helper.sign(params); System.out.println("Signed Request is \"" + requestUrl + "\""); title = fetchTitle(requestUrl); System.out.println("Signed Title is \"" + title + "\""); System.out.println(); } private static String fetchTitle(String requestUrl) { String titles = null; try { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.parse(requestUrl); NodeList titleNodes = doc.getElementsByTagName("Title"); int titleNum = titleNodes.getLength(); for(int i=0; i < titleNum; i++) { Node titleNode = titleNodes.item(i); String title = titleNode.getTextContent(); System.out.println(title); } } catch (Exception e) { throw new RuntimeException(e); } return titles; } }
結果
Pen(ペン) 2016年 11/15 号 [ハリー・ポッター完全読本。] Pen(ペン) 2016年 11/1号 [ゴッホ、君は誰?] ペン太のこと(8): イブニング 【音声ペン付き】ペンがおしゃべり! 英検に役立つ 小学えいご絵じてん800 改訂版 30日できれいな字が書けるペン字練習帳 (TJMOOK) 【音声ペン付き】ペンがおしゃべり! ベビー&キッズえいご絵じてん500 改訂版 ワンランク上の美文字が書ける!! 極める! ペン字・筆文字練習帳 (COSMIC MOOK) Pen(ペン) 2016年 12/1 号 [雑誌] 【音声ペン付き】ペンがおしゃべり! えいご絵じてんプレミアムセット 改訂版 大人の筆ペン字練習帳 春夏秋冬、季節のおたより篇 Signed Title is "null"
注意点
リクエスト制限が1時間に3600回以下らしいので
設計に工夫が必要になるね〜