It seems to be a major communication method recently for communication between servers. Well, these days, every major service distributes APIs, so I'll study a little.
I haven't studied for an hour, so I'm accepting editing!
The API can make the following requests to the server.
Method | What you can do |
---|---|
GET | Get resources |
POST | Creating child resources, adding data to resources, and other processing |
PUT | Update resources, create resources |
DELETE | Delete resource |
HEAD | Resource header(Get metadata) |
OPTIONS | Get methods supported by a resource |
TRACE | Check proxy operation |
CONNECT | Change to tunnel connection for proxy behavior |
Personally, the only thing I use in this is GET POST. If you want to know about business, please check more.
This time, we will create the simplest API, API to get JSON with GET method.
First of all, from the service that delivers JSON.
(I will not explain the controller of Spring MVC anymore ヾ (.> ﹏ <.) ノ)
APIServiceController.java
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.TsugaruInfo.formmodel.RegisterForm;
@RequestMapping(value = "/APITransport")
@RestController
public class APIServiceController {
@RequestMapping(value="APIAccessParametors",produces="application/json;charset=UTF-8")
public String APIAccessParametors() {
String APIResponseJson =
"{\"user\": [\"AtsuAtsuUdon\", \"user\", true],"
+ " \"toot\": [\"It's hot udon noodles!\"]"
+ "CWInfo: {CWSituationIs:[true, \"Something I want to hide\"], \"publicToot\", \"something\"]}";
return APIResponseJson;
}
}
As you can see, it's just returning the string. If you force to raise points ** @RestController and clearly state that it is a Restful service. ** ** Since Japanese character strings are delivered, @RequestMapping produces="application/json;charset=UTF-8" It is specified as.
Now let's fetch the client that receives this using HTTP communication. Apparently Java has a standard ** JAX-RS API ** Rest service and client specification. As an implementation, there is a convenient library called ** jersey **.
Of course, this library is also versioned by ** Spring IO Platform **, so (if you don't know, ggt (ry) Let's embed this library right away. ** [20190115] Addendum Spring IO Platform has finished development (T_T) Please use Spring boot to solve the Spring library **
pom.xml
<!-- jersey -->
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-client</artifactId>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.ext</groupId>
<artifactId>jersey-spring3</artifactId>
</dependency>
<!-- Jackson -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
The library below is a json or xml parser library called Jackson. It will convert the received json string into an object.
Now let's create the client side.
APIRecieverController.java
@RequestMapping(value = "/APITransport")
@Controller
public class APIRecieverController {
@RequestMapping(value="recieverClient")
public ModelAndView recieverClient(Model model) {
ModelAndView mv = new ModelAndView("APIRecieverView");
//Specify HTTP communication settings and URL
//If it is a post method, put the request body here
//HTTP headers can also be included
Client client = ClientBuilder.newClient();
WebTarget target = client.target("http://localhost:8080")
.path("/WebAquarium3.1/APITransport/APIAccessParametors");
String result = "";
//Attempt HTTP communication
try {
result = target.request().get(String.class);
} catch (BadRequestException e) {
System.out.println("Reception failed > <");
throw e;
}
//Send the received json to the view as it is.
//I won't rap with jackson this time
mv.addObject("APIMessage", result);
return mv;
}
}
Basically it is as written in the comment. ** 1. Specify the API URL ** ** 2. Throw a request **
Use the API in the procedure. Finally, create a view that displays this. It says html, but of course this is .jsp
APIRecieverView.html
<%@ page contentType="text/html;charset=UTF-8" pageEncoding="UTF-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<head>
<meta content="ja" http-equiv="Content-Language" />
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<title>HTTPReciever</title>
<body>
<p>The received message of API is</p>
<p>${APIMessage}</p>
<p>is.</p>
</body>
</html>
Just receive the value with **% APIMessage% **. It's easy. Let's run it.
I was able to use the API properly using HTTP communication.
To be honest, this alone cannot be so flashy. When it comes to acquiring authentication information in combination with OAuth2 and Spring Security, it will be a fairly powerful function. (It seems that studying to that extent will be the first)
For the time being, perform HTTP communication with Java. It was a study that felt like holding down the basics.
Reference URL Jersey Client API: How to create a Web API Client in Java http://www.techscore.com/blog/2016/09/20/jersey-client-api/ POST in Jersey Client https://qiita.com/noobar/items/a96e07e441241b1e0215
Recommended Posts