简体   繁体   中英

How to use a Spring Boot API in a java method

I'm new to programming and I got a project to make a rest API. I made one using spring boot to use GET and POST operations. Now I'm trying to get it to work on a simple java application where,

  • The user inserts their first name using the java scanner.
  • Then sends a POST request to send it to a database.

So far the API works fine in Postman but I have no idea on how to add it to java using a method.

( I used this tutorial to make the api : https://www.callicoder.com/spring-boot-rest-api-tutorial-with-mysql-jpa-hibernate/ )

Good you are learning.. keep it up.. Soultion for your question is

You have to implement one RestClient using RestTemplate of Spring or other ( How do you create a REST client for Java? )

Say you have your endpoint http://localhost:8081/api/name

在此处输入图片说明

You have to create RestClient like this ( I have used simple one just for example purpose )

在此处输入图片说明

You should implement a java rest client that call you back end spring boot api that interactes with your database. To do it you can use a lot of java rest client api. See here rest client api

This is how to POST using a spring application as a REST client, assuming you're POST ing JSON , ie the "{ ... }" bit and receving JSON in the return:

HttpHeaders headers = new HttpHeaders();
headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
HttpEntity<String> payload = new HttpEntity<>("{ ... }", headers);

RestTemplate restTemplate = new RestTemplate();
String jsonFromServer = restTemplate.postForObject(url, payload, String.class);

What you can do is:

  1. You will require this json to send data:

{
"firstname" : "xyz"
}

The code is simple just go through this tutorial: http://zetcode.com/java/getpostrequest/

Follow the same steps and you can achieve your goal. Try to replace the Model with your required data.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM