Currently I started developing with API in Java. It was my first time to use API in Java and I managed to implement it, so I will write it in a memorandum sense. First of all, I will show you the general implementation. After that, I will explain it in the following sections.
--[Connect to API URL](#Connect to API URL) -[Use BufferedReader to get response from API](# Use BufferedReader to get response from API) --[Convert JSON string to Java object using ObjectMapper](#Convert JSON string to Java object using ObjectMapper)
In that, I will look at the implementation part of each section and its explanation while looking at the references.
useJson.java
public static JsonNode getResult(String urlString) {
String result = "";
JsonNode root = null;
try {
URL url = new URL(urlString);
HttpURLConnection con = (HttpURLConnection)url.openConnection();
con.connect(); //URL connection
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String tmp = "";
while ((tmp = in.readLine()) != null) {
result += tmp;
}
ObjectMapper mapper = new ObjectMapper();
root = mapper.readTree(result);
in.close();
con.disconnect();
}catch(Exception e) {
e.printStackTrace();
}
return root;
}
useJson.java
URL url = new URL(urlString): //Specify API URL including request parameters
HttpURLConnection con = (HttpURLConnection)url.openConnection();
con.connect(); //Connect to URL
Specify a String type character string as an argument. Pointer a String type character string to the Web. Reference: Class URL
A pointer is a reference (pointer) to an object when it can be accessed with some logical location information.
The logical location information referred to here refers to a location (URL) on the Web.
[Reference: Pointer (Programming)](https://ja.wikipedia.org/wiki/%E3%83%9D%E3%82%A4%E3%83%B3%E3%82%BF_(%E3%83) % 97% E3% 83% AD% E3% 82% B0% E3% 83% A9% E3% 83% 9F% E3% 83% B3% E3% 82% B0))
"Logical" is the state of thinking in a proper way. The meanings of "theory" and "reason" are common to "line". In addition, "theory" also means "discuss", and "reason" also means "words and principles".
In other words, here it is to make a way to the URL (specify the address).
Allow both reading and writing of resources referenced in URLs
openConnection Manipulate parameters that affect connections to remote resources Reference: Class URLConnection
useJson continued.java
String result = "";
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()))); //Receive response
String tmp = "";
while ((tmp = in.readLine) != null){
result += tmp;
}
Efficiently read text from a character input stream by buffering characters, arrays, and lines.
Here, it means to read JSON format text efficiently. Reference: Class BufferedReader
Buffering is when exchanging data between multiple devices and software, compensating for differences in processing speed and transfer speed, and temporarily sending and receiving data to a dedicated storage area in case of communication deceleration or interruption. Save it in.
In other words, save some data at the beginning of connecting to the API with the request, and when it has accumulated to some extent, read the response safely and speed up the processing speed. Reference: Buffering [buffering] Buffering
InputStreamReader acts as a bridge from the byte stream to the character stream
Here, it means to drop the JSON format response into the character stream. Reference: Class InputStreamReader
(HttpURLConnection)con.getInputStream
Returns an input stream that receives input from this connection. When reading from the returned input stream, a SocketTimeoutException is thrown if the read timeout expires before the data becomes readable.
"This connection" is a JSON response. Reference: getInputStream
in.readLine()
Read a line of text.
Read the response line by line [Reference: Summary of class BufferedReader method readLine ()] (https://docs.oracle.com/javase/jp/8/docs/api/java/io/BufferedReader.html)
useJson continued ②.java
JsonNode jsonResult = null; //Initialization
ObjectMapper mapper = new ObjectMapper();
jsonResult = mapper.readTree(result);
in.close();
con.disconnect();
Can convert between Java objects and JSON strings.
Reference: Jackson usage memo JSON string → Java object Description
mapper.readTree(result)
Then, ObjectMapper.readTree reads the root node when the JSON file data is made into tree structure data as a JsonNode type object. Reference: Read data with JSON library Jackson for Java
A tree structure is one of the data structures, and one element (node) has multiple child elements, and one child element has multiple grandchild elements. The deeper the hierarchy, the more branched. The structure. It is called this because it resembles a tree branching from trunk to branch and from branch to leaf.
The elements that make up the tree structure are called nodes, and the nodes have a parent-child relationship. A node without a parent is called a root node, and a node without a child is called a leaf node.
[Reference: Tree structure] Tree structure ](http://e-words.jp/w/%E6%9C%A8%E6%A7%8B%E9%80%A0.html)
In other words, it is readTree
that plays the role of acquiring the data (root node) at the top of the tree structure.
in.close(); End of BufferedReader class
con.disconnect(); Termination (disconnection) of URL connection
I'm tired ... w I think it looks like this when connecting to a Json format API. By the way, if you handle Json in Java, you will need to include some libraries, but I think there are some that are unnecessary, so I will add them as soon as I understand. The following are currently included.
If you have any suggestions or questions in this article, I would appreciate it if you could comment.
Recommended Posts