[JAVA] I made a function to register images with API in Spring Framework. Part 2 (Client Edition)

I made an API, so I will try to connect.

How to make API here

Connect using Jersey.

The whole picture of the client I made looks like this

ImageIOController.java



	@RequestMapping(value = "/imageCompleteApi", method = RequestMethod.POST)
	public ModelAndView imageUploadCompleteApi(ImageUploadFormApi imageUploadFormApi,
			Principal principal) {
		
		//Get credentials
        Authentication auth = (Authentication)principal;
        LoginUserDetails LoginUser = (LoginUserDetails)auth.getPrincipal();
		
		//Get binary data
		Integer FileSize = (int) (imageUploadFormApi.getImage().getSize());
		byte[] imageBinary = new byte[FileSize];
		
		try {
			 imageBinary = imageUploadFormApi.getImage().getBytes();
		} catch (IOException e) {
			//TODO auto-generated catch block
			e.printStackTrace();
		}

		//Request preparation
		PictureMaster pictureMaster = new PictureMaster();
		
		pictureMaster.setOriginalName(imageUploadFormApi.getImage().getOriginalFilename());
		pictureMaster.setPictureName(imageUploadFormApi.getFilename());
		pictureMaster.setExtension(imageUploadFormApi.getImage().getOriginalFilename()
				.substring(imageUploadFormApi.getImage().getOriginalFilename().length() - 4, imageUploadFormApi.getImage().getOriginalFilename().length()));
		pictureMaster.setBase64string(Base64.getEncoder().encodeToString(imageBinary));
		pictureMaster.setUploadUserId(LoginUser.getUserId());
	    //Call the API to register the image
		

		ObjectMapper mapper = new ObjectMapper();
		
		Entity<String> requestBody = null;
		String result = null;
		
		//Set the header.
		MultivaluedMap<String, Object> headers = new MultivaluedHashMap<>();
		headers.putSingle("X-SUBDOMEIN", "api");
		
		try {
			requestBody = Entity.json(mapper.writeValueAsString(pictureMaster));
			
			//Send a post request to the API to your server.
			Client client = ClientBuilder.newClient();
			WebTarget target = client.target("http://api.localhost:8080")
				    .path("/WebAquarium3.1/api/picture/addPicture");
			
			result = target
					.request()
					.headers(headers)
					.post(requestBody, String.class);
			
			
		} catch (IOException e1) {
			//TODO auto-generated catch block
			e1.printStackTrace();
		}
		
                		
        //Convert the received JSON to a class
		
		System.out.println(result);
		ModelAndView mv = new ModelAndView("ImageComplete");
		return mv;
	}

In the first half, you just process the acquired data according to the DB. The important thing is

ImageIOController.java


ObjectMapper mapper = new ObjectMapper();

It is a process from.

The processing flow is like this.

  1. Set the required headers for the API.
  2. Prepare request Entity
  3. Set the header and request and execute POST.

First, here, convert the request to Json format and prepare it.

1. Set the required headers for the API.

ImageController.java



		//Set the header.
		MultivaluedMap<String, Object> headers = new MultivaluedHashMap<>();
		headers.putSingle("X-SUBDOMEIN", "api");

I will set the header required for the request. ** MultivaluedHashMap ** Header class for Jersey

2. Prepare request Entity

ImageController.java


			requestBody = Entity.json(mapper.writeValueAsString(pictureMaster));

Next, set the Json data in the Entity class. Json data is generated using Jackson.

3. Set the header and request and execute POST.

ImageController.java


			//Send a post request to the API to your server.
			Client client = ClientBuilder.newClient();
			WebTarget target = client.target("http://api.localhost:8080")
				    .path("/WebAquarium3.1/api/picture/addPicture");
			
			result = target
					.request()
					.headers(headers)
					.post(requestBody, String.class);

First, use ** ClientBuilder ** and ** WebTarget **, I will set which address of which domain to connect to

Then set the headers and posts in headers and post. The final ** String.class ** means the final "I'll receive the response as a string".

It seems that you can get it even with your own class if you set something called JerseyProvider, but I will not do it this time (Mendokusa (ry))

Let's connect

Let's connect now.

I will omit the operation of the screen a little. ; Tsu Д `)

I can confirm that the response is back. image.png

The image has been registered in the DB! image.png

Recommended Posts

I made a function to register images with API in Spring Framework. Part 2 (Client Edition)
I made a function to register images with API in Spring Framework. Part 1 (API edition)
I created an api domain with Spring Framework. Part 2
I made a Restful server and client in Spring.
I made a simple search form with Spring Boot + GitHub Search API.
Even in Java, I want to output true with a == 1 && a == 2 && a == 3 (PowerMockito edition)
"Teacher, I want to implement a login function in Spring" ① Hello World
I made a mosaic art with Pokemon images
Even in Java, I want to output true with a == 1 && a == 2 && a == 3 (black magic edition)
I tried to make a login function in Java
I want to define a function in Rails Console
I tried to create a shopping site administrator function / screen with Java and Spring
Minimum configuration sample of RESTful API in Jersey + Spring Framework
Spring Boot: Restful API sample project
Java --Jersey Framework vs Spring Boot
spring boot access authorization RESTful API
Implement REST API in Spring Boot
Launch (old) Spring Boot project in IntelliJ
Create Java Spring Boot project in IntelliJ
Major changes in Spring Framework 5.0 core functionality
Sample code to call Yahoo! Shopping Product Search (v3) API in Spring RestTemplate
I made a function to register images with API in Spring Framework. Part 1 (API edition)
[Beginner] I made a program to sell cakes in Java
I want to make a function with kotlin and java!
I searched for a web framework with Gem in Ruby
Even in Java, I want to output true with a == 1 && a == 2 && a == 3
I tried to make a client of RESAS-API in Java
Rails was difficult, so I made something like a controller of Spring Framework to take a break
I tried to create an API to get data from a spreadsheet in Ruby (with service account)
I want to add a browsing function with ruby on rails
02. I made an API to connect to MySQL (MyBatis) from Spring Boot
I made a reply function for the Rails Tutorial extension (Part 1)
I made a reply function for the Rails Tutorial extension (Part 5):
I wanted to make JavaFX programming easier with the Spring Framework
I tried to make a group function (bulletin board) with Rails
I made a GUI with Swing
I made a simple recommendation function.
I created an api domain with Spring Framework. Part 2
I searched for a web framework with Gem in Ruby
I summarized the collection framework.
I want to display images with REST Controller of Java and Spring!
I made an app to scribble with PencilKit on a PDF file
I want to select multiple items with a custom layout in Dialog
I tried to build a Firebase application development environment with Docker in 2020
I examined the flow of TCP communication with Spring Integration (client edition)
I want to display a PDF in Chinese (Korean) with thin reports
I wrote a Lambda function in Java and deployed it with SAM
Create a SPA with authentication function with Rails API mode + devise_token_auth + Vue.js 3 (Rails edition)
I want to ForEach an array with a Lambda expression in Java
[LINE BOT] I made a ramen BOT with Java (Maven) + Heroku + Spring Boot (1)
I made a reply function for Rails Tutorial extension (Part 2): Change model
I made a risky die with Ruby
I made a rock-paper-scissors app with kotlin
I made a rock-paper-scissors app with android
Let's create a TODO application in Java 2 I want to create a template with Spring Initializr and make a Hello world
I tried to make a machine learning application with Dash (+ Docker) part3 ~ Practice ~
I tried to implement a function equivalent to Felica Lite with HCE-F of Android
Introduced # 10 devise_token_auth to build a bulletin board API with authentication authorization in Rails 6
[Rails / JavaScript / Ajax] I tried to create a like function in two ways.
03. I sent a request from Spring Boot to the zip code search API
Even in Java, I want to output true with a == 1 && a == 2 && a == 3 (Javassist second decoction)
[Go To Travel] I searched for a plan with a quo card in Jalan
I made a THETA API client that can be used for plug-in development
Introducing # 15 pundit to build a bulletin board API with authentication authorization in Rails 6
I tried printing a form with Spring MVC and JasperReports Extra edition (Variables edition)
I tried printing a form with Spring MVC and JasperReports Extra edition (image edition)
SpringSecurity I was addicted to trying to log in with a hashed password (solved)
I tried to clone a web application full of bugs with Spring Boot
I made a sample of how to write delegate in SwiftUI 2.0 using MapKit
Even in Java, I want to output true with a == 1 && a == 2 && a == 3 (Royal road edition that is neither magic nor anything)
04. I made a front end with SpringBoot + Thymeleaf
I made a gender selection column with enum