Note that Yahoo!'S product search API will have new specifications. https://developer.yahoo.co.jp/webapi/shopping/shopping/v3/itemsearch.html
The structure of JSON has changed due to the need to encode the search word. We will use Jackson to handle JSON. Please check the introduction by yourself.
As a change from the old specification, UTF-8 encoding is required.
java
//Application ID
final String appID = "Application ID";
//Search word UTF-8 encoding
String query = request.getParameter("searchWord");
String encodedQuery = URLEncoder.encode(query, "UTF-8");
//URL creation
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();
Note that the JSON structure is different from the old specifications. This time, we will extract the top 10 product names and prices 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<>();
//Extract information for 10 items and store it in the list
for(int i = 0; i < 10; i++){
//Since the value of hits is an array, specify the element number as 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);
Recommended Posts