Java spring post json

Работа с JSON и XML (преобразование объектов) в Spring MVC. Формирование ответа и обработка запроса

Работа с JSON и XML (преобразование объектов) в Spring MVC. Формирование ответа и обработка запроса (RESTful веб-сервис). Применение RestTemplate в Spring MVC.

Обзор приложения Spring MVC + AngularJS + Bootstrap + HTML5
Используемые технологии и библиотеки

1. Описание задачи

В этой части будет рассмотрена работа приложения Spring MVC с форматами JSON и XML (RESTful веб-сервис). Будет показана возможность преобразовывать Java объекты в эти форматы, а так же формировать ответ в JSON или XML виде на запрос клиента. Для примера будет использован сторонний источник данных (внешний интернет ресурс), который будет предоставлять данные в том или ином формате. Таким образом здесь мы рассмотрим:

  • Преобразование POJO (Plain Old Java Object) объектов в формат XML
  • Преобразование POJO объектов в формат JSON
  • Использование аннотаций @ResponseBody , @RestController , @XmlRootElement , @XmlElement
  • Использование RestTemplate

2. Структура проекта

Классы находятся в пакете rest. Во вложенном пакете model находятся классы объектов, которые мы будем преобразовывать в XML или JSON формат ( DBLogJSON , DBLogsXML , RestPostsModel , RestUserModel и т.д.). На уровень выше находятся два контроллера ( RestController и RestTemplateController ), которые будут демонстрировать различные способы работы с REST сервисами. Например, класс RestTemplateController обращается к внешнему сайту (http://jsonplaceholder.typicode.com), который возвращает данные в ответ на запросы, посылаемые нашим приложением.

Читайте также:  Градиент фон css анимированный

Создан один файл представление — rest.jsp из одноименного пакета. На этой страничке будет доступен вызов того или иного метода из контроллеров.

3. pom.xml

Отдельной строкой была добавлена зависимость Java Architecture for XML Binding (JAXB). Этот пакет входит в Java SE и можно было бы его не добавлять для этого проекта, но здесь было выделить его в учебных целях.

Источник

Post JSON to spring REST webservice

After making a GET request to a REST service the natural progression is to POST information back to the server. In this episode we will look at how to post json to spring controller and have it automatically convert JSON to arraylist, object or multiple objects.

Detailed Video Notes

Understanding @RequestBody

The first thing to understand is how json binds to a java object. The @RequestBody method parameter annotation should bind the json value in the HTTP request body to the java object by using a HttpMessageConverter. In episode 13 how to return XML in REST, we discussed the responsibility of HttpMessageConverter. To recap HttpMessageConverter is responsible for converting the HTTP request message to an assoicated java object. In our case want to convert JSON to a java object when a request is made. Spring will look specifically for a HttpMessageConverter assoicated to the mime type to perform the conversion. Since spring boot configures it automatically if jackson is on our class path MappingJackson2MessageConverter is used. Alternatively you can configure GsonHttpMessageConverter based on google gson library which was offically release in spring version 4.1.

In code we annotate the method parameter with spring @RequestBody which looks like:

@RequestMapping(value = "/", method = RequestMethod.POST) public ResponseEntityCar> update(@RequestBody Car car)  . >

Project set up

Creating a project

We will create a new project with spring boot and create a POJO object Car which will post to a spring controller. One thing to note in our snippets is we won’t discuss REST api design topic or make the actual update to a persistence layer.

public class Car  private String VIN; private String color; private Integer miles; //. >

Get request

Before we post JSON, lets create a method to return a Car and make a request to http://localhost:8080/. You will notice that we are using ResponseEntity as the method return type. ResponseEntity is a class that allows you to modify request and response headers. An important design aspect of REST services is also to return the proper HTTP status code and in this case a 200.

@RequestMapping(value = "/") public ResponseEntityCar> get()  Car car = new Car(); car.setColor("Blue"); car.setMiles(100); car.setVIN("1234"); return new ResponseEntityCar>(car, HttpStatus.OK); >

Which should return a json response:

 color: "Blue" miles: 100 vin: "1234" >

Json to java object

You might want to update the Car object by posting json to a URL. A more detailed user story would be, as a user I want to be able update attributes of my car. We will create @RequestMapping and specify method = RequestMethod.POST which will tell spring to use this method when a post occurs. When the post is made lets increment the miles by 100.

@RequestMapping(value = "/", method = RequestMethod.POST) public ResponseEntityCar> update(@RequestBody Car car)  if (car != null)  car.setMiles(car.getMiles() + 100); > // TODO: call persistence layer to update return new ResponseEntityCar>(car, HttpStatus.OK); >

Using the sample JSON above, lets make a request using advanced rest client chrome plugin and result should increment the miles field by 100.

 "color":"Blue", "miles":200, "vin":"1234" >

Json to arraylist

Next, you might have a life event where you inherit a car, get married or your child starts to drive (good luck!). Now we have a series of cars we want to update the mileage. Lets create a new request mapping to http://localhost:8080/cars which accepts a json array as a parameter. Again, we will increment mileage by 100 using a java 8 foreach loop.

@RequestMapping(value = "/cars", method = RequestMethod.POST) public ResponseEntityListCar>> update(@RequestBody ListCar> cars)  cars.stream().forEach(c -> c.setMiles(c.getMiles() + 100)); // TODO: call persistence layer to update return new ResponseEntityListCar>>(cars, HttpStatus.OK); >

Modifing our sample json above we will convert it to a json array and add an additonal node. Lets make a request using advanced rest client chrome plugin and we should see the miles increment by 100.

[  "color":"Blue", "miles":200, "vin":"1234" >,  "color":"Red", "miles":500, "vin":"1235" > ]

Passing multiple json objects

If you want to send multiple json objects to a controller, you will need to create a wrapper object that represents your request due to the request containing the entire JSON content. We will create a Truck object, a RequestWrapper object and a new @RequestMapping.

Truck object

public class Truck  private String VIN; private String color; private Integer miles; //. >

RequestWrapper object

The RequestWrapper will contain a List of Cars and a single truck object.

public class RequestWrapper  ListCar> cars; Truck truck; //. >

New @RequestMapping

@RequestMapping(value = "/carsandtrucks", method = RequestMethod.POST) public ResponseEntityRequestWrapper> updateWithMultipleObjects( @RequestBody RequestWrapper requestWrapper)  requestWrapper.getCars().stream() .forEach(c -> c.setMiles(c.getMiles() + 100)); // TODO: call persistence layer to update return new ResponseEntityRequestWrapper>(requestWrapper, HttpStatus.OK); >

Making the request

Again, we will use advanced rest client to http://localhost:8080/carsandtrucks with the following JSON.

 "cars":[  "color":"Blue", "miles":100, "vin":"1234" >,  "color":"Red", "miles":400, "vin":"1235" > ], "truck": "color":"Red", "miles":400, "vin":"1235" > >

Thanks for joining in today’s level up lunch, have a great day.

Post JSON to spring REST webservice posted by Justin Musgrove on 22 August 2014

Tagged: java, java-tutorial, and spring

All the code on this page is available on github: View the source

Источник

RestTemplate POST Request with JSON and Headers

In this article, you will learn how to make different kinds of HTTP POST requests by using the RestTemplate class in a Spring Boot application.

An HTTP POST request is used to create a new resource. The RestTemplate class provides several template methods like postForObject() , postForEntity() , and postForLocation() for making POST requests.

The first two methods are very similar to what we discussed in RestTemplate’s GET request tutorial. The last method returns the location of the newly created resource instead of the complete resource.

To make a simple HTTP POST request using RestTemplate, you can use the postForEntity method and pass the request body parameters as a map object:

// request url String url = "https://reqres.in/api/users"; // create an instance of RestTemplate RestTemplate restTemplate = new RestTemplate(); // request body parameters MapString, String> map = new HashMap>(); map.put("name", "John Doe"); map.put("job", "Java Developer"); // send POST request ResponseEntityVoid> response = restTemplate.postForEntity(url, map, Void.class); // check response if (response.getStatusCode() == HttpStatus.OK)  System.out.println("Request Successful"); > else  System.out.println("Request Failed"); > 

To make a POST request with the JSON request body, we need to set the Content-Type request header to application/json . The following example demonstrates how to make an HTTP POST request with a JSON request body:

// request url String url = "https://jsonplaceholder.typicode.com/posts"; // create an instance of RestTemplate RestTemplate restTemplate = new RestTemplate(); // create headers HttpHeaders headers = new HttpHeaders(); // set `content-type` header headers.setContentType(MediaType.APPLICATION_JSON); // set `accept` header headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON)); // request body parameters MapString, Object> map = new HashMap>(); map.put("userId", 1); map.put("title", "Spring Boot 101"); map.put("body", "A powerful tool for building web apps."); // build the request HttpEntityMapString, Object>> entity = new HttpEntity>(map, headers); // send POST request ResponseEntityString> response = restTemplate.postForEntity(url, entity, String.class); // check response if (response.getStatusCode() == HttpStatus.CREATED)  System.out.println("Request Successful"); System.out.println(response.getBody()); > else  System.out.println("Request Failed"); System.out.println(response.getStatusCode()); > 
// request url String url = "https://reqres.in/api/login"; // create an instance of RestTemplate RestTemplate restTemplate = new RestTemplate(); // create headers HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON)); // add basic authentication headers.setBasicAuth("username", "password"); // build the request HttpEntity request = new HttpEntity(headers); // send POST request ResponseEntityString> response = restTemplate.postForEntity(url, request, String.class); // check response if (response.getStatusCode() == HttpStatus.OK)  System.out.println("Login Successful"); > else  System.out.println("Login Failed"); > 

RestTemplate allows you to map the JSON response directly to a Java object. Let us first create a simple Post class:

public class Post implements Serializable  private int userId; private int id; private String title; private String body; public Post()  > public Post(int userId, int id, String title, String body)  this.userId = userId; this.id = id; this.title = title; this.body = body; > // getters and setters, equals(), toString() . (omitted for brevity) > 
// request url String url = "https://jsonplaceholder.typicode.com/posts"; // create an instance of RestTemplate RestTemplate restTemplate = new RestTemplate(); // create headers HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON)); // create a post object Post post = new Post(101, 1, "Spring Boot 101", "A powerful tool for building web apps."); // build the request HttpEntityPost> request = new HttpEntity>(post, headers); // send POST request ResponseEntityPost> response = restTemplate.postForEntity(url, request, Post.class); // check response if (response.getStatusCode() == HttpStatus.CREATED)  System.out.println("Post Created"); System.out.println(response.getBody()); > else  System.out.println("Request Failed"); System.out.println(response.getStatusCode()); > 

Check out the Making HTTP Requests using RestTemplate in Spring Boot guide for more RestTemplate examples. ✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.

You might also like.

Источник

Оцените статью