[Java] I tried to implement Yahoo API product search

Introduction

I tried to make something like an EC site using Yahoo's API, but I fell into a situation where I didn't know how to use it at all. I didn't understand it even if I looked it up, and it was quite difficult, so I will record it including the meaning of the memo.

By the way, I have been learning Java for about 3 months.

What you want to achieve

  1. Receive search keywords from HTML form
  2. Pass the search keyword to the API in the request
  3. Receive JSON of product information from API in response
  4. Extract the element from JSON and set it in JavaBeans
  5. Store JavaBeans in ArrayList
  6. Store ArrayList in request scope and forward to jsp for result output

I wrote the code

Pass search keywords to API in request

Apparently, the way to send a request to the API is to connect to the URL, There was a class for that. That is the ** HttpURLConnection class **.

The basic steps are

  1. Get the URL for API connection
  2. Get a connection
  3. Connection settings
  4. Connection

It's like that.

-Face with URLConnection (HttpURLConnection) ~ Get data with GET method ~

  //Application ID
  String appid = "Application ID";
  //Receives product keywords and stores them in String type
  request.setCharacterEncoding("UTF-8");
  String query = request.getParameter("searchVal");
  //Request URL
  String url = "https://shopping.yahooapis.jp/ShoppingWebService/V1/json/itemSearch?appid="+appid+"&query="+query;
  //URL generation for API connection
  URL url4conn = new URL(url);
  //Get a connection to the URL for the API connection
  HttpURLConnection conn = (HttpURLConnection)url4conn.openConnection();
  //Specify HTTP method for GET
  conn.setRequestMethod("GET");
  //Do not allow body submission of request
  conn.setDoOutput(false);
  //Allow body transmission of response
  conn.setDoInput(true);
  //Connect
  conn.connect();

Receive JSON of product information from API in response

Apparently, to get the response from the API, you can read the response using BufferedReader. However, since you can get ** JASON character string ** at the stage of reading, you need to convert it to ** JASON node (type for JSON) ** using the library.

The basic steps are

  1. Read response
  2. Convert JSON string to JSON node

It's like that.

  //Read response(Get JASON string)
  BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
  String json = br.readLine();
            
  //Read JSON string and convert to JsonNode object
  ObjectMapper mapper = new ObjectMapper();
  JsonNode root = mapper.readTree(json);

Extract elements from JSON and set in JavaBeans

The basic steps are

  1. ** Extract a specific element from a JSON node ** and store it in a String type
  2. Set it in JavaBeans

It's like that.

Use ** JsonNode.get () ** to retrieve a specific element from a JSON node.

--Read data with JSON library Jackson for Java

  //Generate an ArrayList that stores Beans containing product search results
            ArrayList<productDataBeans> pdbList = new ArrayList<productDataBeans>();
            
  //Extract 10 elements from JSON and store in String type
  //Set it in Beans and store Beans in ArrayList
  for(int i = 0; i <= 9; i++) {
        String hitNum = String.valueOf(i);
        String imageURL = root.get("ResultSet").get("0").get("Result").get(hitNum).get("Image").get("Small").textValue();
        String productName = root.get("ResultSet").get("0").get("Result").get(hitNum).get("Name").textValue();
        String price = root.get("ResultSet").get("0").get("Result").get(hitNum).get("Price").get("_value").textValue();
        int SearchResultNum = root.get("ResultSet").get("totalResultsAvailable").asInt();
                
        //Create an instance of Beans to store product search results
        productDataBeans pdb = new productDataBeans();
        pdb.setImageURL(imageURL);
        pdb.setProductName(productName);
        pdb.setPrice(price);  
                
        pdb.setQuery(query);
        pdb.setSearchResultNum(SearchResultNum);
                
        pdbList.add(pdb);
   }
            
  //Store ArrayList in request scope
  request.setAttribute("resultData", pdbList);

  br.close();
            
  request.getRequestDispatcher("/search.jsp").forward(request, response);

Supplement --About the JSON library

I mentioned that you need to convert the JSON string you read into a JSON node, but in the case of Jackson, you need three libraries.

Jackson-core -Jackson-annotationsJackson-databind

You can download it by selecting the linked version and pressing the bundle button.

Recommended Posts

[Java] I tried to implement Yahoo API product search
[Java] New Yahoo! Product Search API Implementation
I tried to implement deep learning in Java
I tried to implement TCP / IP + BIO with JAVA
I tried to implement Firebase push notification in Java
Try to implement using Rakuten product search API (easy)
I tried to implement Stalin sort with Java Collector
I tried to implement the Euclidean algorithm in Java
I tried to interact with Java
I tried using Java8 Stream API
I tried to summarize Java learning (1)
I tried to summarize Java 8 now
I tried using Elasticsearch API in Java
I tried to summarize Java lambda expressions
I tried to solve AOJ's Binary Search
I tried to implement the Iterator pattern
I tried to summarize the Stream API
Sample code to call the Yahoo! Local Search API in Java
I tried to implement ModanShogi with Kinx
I tried to make Basic authentication with Java
java I tried to break a simple block
[Java] Create something like a product search API
I tried to output multiplication table in Java
I tried to create Alexa skill in Java
I tried to implement a server using Netty
I tried to break a block with java (1)
Sample code to call Yahoo! Shopping Product Search (v3) API with HTTP Client API officially introduced from Java 11
Rails API mode I tried to implement the keyword multiple search function using arrays and iterative processing.
Sample code to call Yahoo! Shopping Product Search (v3) API in Spring RestTemplate
I tried Mastodon's Toot and Streaming API in Java
[Java 11] I tried to execute Java without compiling with javac
I tried using Google Cloud Vision API in Java
[Java] I tried to solve Paiza's B rank problem
I tried to operate SQS using AWS Java SDK
# 2 [Note] I tried to calculate multiplication tables in Java.
I tried to create a Clova skill in Java
I tried to make a login function in Java
I tried to draw animation with Blazor + canvas API
~ I tried to learn functional programming in Java now ~
I tried to find out what changed in Java 9
I tried Drools (Java, InputStream)
[Java] Introduction to Stream API
I tried to verify yum-cron
[Java] How to implement multithreading
I tried to make a product price comparison tool of Amazon around the world with Java, Amazon Product Advertising API, Currency API (2017/01/29)
I tried metaprogramming in Java
[Swift] I tried to implement exception handling for vending machines
I tried to implement the like function by asynchronous communication
I tried to create a java8 development environment with Chocolatey
I tried to modernize a Java EE application with OpenShift.
[JDBC] I tried to access the SQLite3 database from Java.
I want to implement a product information editing function ~ part1 ~
[Swift] I tried to implement the function of the vending machine
I tried to introduce UI animation to Pokedex using Poké API
I want to use the Java 8 DateTime API slowly (now)
I tried to make Java Optional and guard clause coexist
I tried to link chat with Minecraft server with Discord API
[Rails] I tried to implement batch processing with Rake task
I tried to convert a string to a LocalDate type in Java
I tried using Dapr in Java to facilitate microservice development
I tried to implement a buggy web application in Kotlin