0
0

More than 3 years have passed since last update.

[Java]新仕様のYahoo!商品検索API実装

Last updated at Posted at 2020-06-12

Yahoo!の商品検索APIが新仕様になるのでメモ。
https://developer.yahoo.co.jp/webapi/shopping/shopping/v3/itemsearch.html

検索ワードのエンコードが必要になり、JSONの構造が変わりました。
JSONを扱うためにJacksonを利用します。導入は各自で調べてください。

やること

1.HTMLから受け取った検索ワードをAPIに送る。
2.JSONを受け取り必要な情報を抜き出してフォワードする。

1.HTMLから受け取った検索ワードをAPIに送る。

旧仕様からの変更点として、UTF-8エンコードが必要になりました。

java
//アプリケーションID
final String appID = "アプリケーションID";

//検索ワードをUTF-8エンコード
String query = request.getParameter("searchWord");
String encodedQuery = URLEncoder.encode(query, "UTF-8");

//URL作成
String url = "https://shopping.yahooapis.jp/ShoppingWebService/V3/itemSearch"
               + "?appid=" + appID + "&query=" + encodedQuery;
URL conUrl = new URL(url);

//接続
HttpURLConnection con = (HttpURLConnection)conUrl.openConnection();
con.connect();

2.JSONを受け取り必要な情報を抜き出してフォワードする。

JSONの構造が旧仕様と異なるので注意。
今回は検索結果から先頭10件の商品名と値段を抜き出します。

java
//json文字列の読み取り
BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));
String json = br.readLine();
br.close();

//json文字列をJsonNodeに変換
ObjectMapper mapper = new ObjectMapper();
JsonNode node = mapper.readTree(json);

//JavaBeansを格納するArrayList
ArrayList<DataBeans> list = new ArrayList<>();

//10件分の情報を取り出してリストに格納
for(int i = 0; i < 10; i++){
  //hitsのvalueは配列なので整数で要素番号を指定する
  String name = node.get("hits").get(i).get("name").textValue();
  int price = node.get("hits").get(i).get("price").asInt();

  //情報をJavaBeansにセット
  DataBeans bean = new DataBeans();
  bean.setName(name);
  bean.setPrice(price);

  list.add(bean);
}
request.setAttribute("resultData", list);
request.getRequestDispatcher("searchResult.jsp").forward(request, response);
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0