[Java] [Java] Implementation of new Yahoo! product search API

1 minute read

Note that Yahoo!’s product search API has new specifications. https://developer.yahoo.co.jp/webapi/shopping/shopping/v3/itemsearch.html

The JSON structure has changed as search words need to be encoded. Use Jackson to handle JSON. Please check the introduction by yourself.

things to do

  1. Send the search word received from HTML to API.
  2. Receive JSON and extract necessary information and forward.

1. Send the search word received from HTML to the API.

As a change from the old specification, UTF-8 encoding is required.

java


// application id
final String appID = "application ID";

// UTF-8 encoding search word
String query = request.getParameter("searchWord");
String encodedQuery = URLEncoder.encode(query, "UTF-8");

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

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

2. Receive JSON and extract necessary information and forward.

Note that the JSON structure is different from the old specification. This time, the top 10 product names and prices are extracted from the search results.

java


// read json string
BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));
String json = br.readLine();
br.close();

//Convert json string to JsonNode
ObjectMapper mapper = new ObjectMapper();
JsonNode node = mapper.readTree(json);

//ArrayList that stores JavaBeans
ArrayList<DataBeans> list = new ArrayList<>();

Retrieves information for 10 cases and stores it in a list
for(int i = 0; i <10; i++){
  //The value of hits is an array, so specify the element number with an integer
  String name = node.get("hits").get(i).get("name").textValue();
  int price = node.get("hits").get(i).get("price").asInt();
  
  //Set information in 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);

Tags: ,

Updated: