[JAVA] I made a Restful server and client in Spring.

I learned a little about API.

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!

About the thing called API

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.

Deliver the API.

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.

Create RestClient.

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.

image.png

I was able to use the API properly using HTTP communication.

Summary

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

I made a Restful server and client in Spring.
[Ruby] I made a simple Ping client
I made a function to register images with API in Spring Framework. Part 2 (Client Edition)
I made a primality test program in Java
I made a Ruby extension library in C
I made a simple calculation problem game in Java
[Ruby] I made a crawler with anemone and nokogiri.
What I learned when building a server in Java
I made a function to register images with API in Spring Framework. Part 1 (API edition)
I made roulette in Java.
I made a chat app.
I made a server side of an online card game ⑤
I made a server side of an online card game ③
[Beginner] I made a program to sell cakes in Java
I made a server side of an online card game ⑥
I tried JAX-RS and made a note of the procedure
I made a server side of an online card game ④
I made a server side of an online card game ②
I tried to make a client of RESAS-API in Java
I made a simple MVC sample system using Spring Boot
I tried Spring Boot introductory guide [Building a RESTful Web Service]
I tried printing a form with Spring MVC and JasperReports 1/3 (JasperReports settings)
Ruby: I made a FizzBuzz program!
I created a PDF in Java.
I made a Ruby container image and moved the Lambda function
I made a shopify app @java
I participated in JJUG CCC 2019 Spring
I made a GUI with Swing
I recently made a js app in the rumored Dart language
[Wire Mock] I want to set up a stub / mock server in Java and perform E2E tests.
I made a simple search form with Spring Boot + GitHub Search API.
Implement a gRPC client in Ruby
I wrote a route search program in TDD and refactored it
I made a simple recommendation function.
I made an annotation in Java.
Spring Boot Introductory Guide I tried [Consuming a RESTful Web Service]
I made a matching app (Android app)
I made a package.xml generation tool.
[Android] I made a pedometer app.
Create a Spring Boot project in intellij and exit immediately after launching
I tried printing a form with Spring MVC and JasperReports 2/3 (form template creation)
I was in trouble at work, so I made a plugin for IntelliJ
I can't find Pivotal tc server Developer Edition in Spring Tool Suite
How to create a server executable JAR and WAR with Spring gradle
I wrote a Lambda function in Java and deployed it with SAM
I made a class that can use JUMAN and KNP from Java
[LINE BOT] I made a ramen BOT with Java (Maven) + Heroku + Spring Boot (1)
"Teacher, I want to implement a login function in Spring" ① Hello World
I tried a calendar problem in Ruby
I made an eco server with scala
I made a risky die with Ruby
I made a plugin for IntelliJ IDEA
I made a rock-paper-scissors app with kotlin
I made a calculator app on Android
What I got into @Transactional in Spring
I made a new Java deployment tool
I made a rock-paper-scissors app with android
[* Java *] I participated in JJUG CCC 2019 Spring
I made a bulletin board using Docker 1
I tried embedding a formula in Javadoc
When I defined a session scope bean in Spring Boot, it behaved strangely and needed to be adjusted.