How to post a Form data from Client side to server using RestTemplate?

Viewed 65

For client side i used tomcat 8080 port and for server side i used tomcat 8081 port. I just tried to post Form data to server side using RestTemplate. Is there is any specific way to doing this?

And i tried to do this as follows,

   { @RequestMapping(value="/addBook")
   public String addBook(Book book){
    
    RestTemplate restTemplate = new RestTemplate();
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

    ResponseEntity<Book> response = restTemplate.postForEntity(
              "http://localhost:8081/api/addbook", book, Book.class);                
    System.out.println(response.getBody());
    return "Home";}

this is my form,

        <h1>Form</h1>
        <form action="addBook">
            <input type="text" name="name"><br>
            <input type="text" name="author"><br>
             <input type="text" name="stock"><br>
             <input type="submit" ><br>
        </form>

And this is my Book class,

package com.example.libraryfrontend.entity;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;

@JsonIgnoreProperties(ignoreUnknown = true)
public class Book {
private String name;
private String author;
private Integer stock;

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getAuthor() {
    return author;
}

public void setAuthor(String author) {
    this.author = author;
}

public Integer getStock() {
    return stock;
}

public void setStock(Integer stock) {
    this.stock = stock;
}}

and this is error i faced,


> Error while extracting response for type [class com.example.libraryfrontend.entity.Book] and content type [application/json;charset=UTF-8]; nested exception is org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Unrecognized token 'Book': was expecting (JSON String, Number, Array, Object or token 'null', 'true' or 'false'); nested exception is com.fasterxml.jackson.core.JsonParseException: Unrecognized token 'Book': was expecting (JSON String, Number, Array, Object or token 'null', 'true' or 'false') at [Source: (PushbackInputStream); line: 1, column: 6]
org.springframework.web.client.RestClientException: Error while extracting response for type [class com.example.libraryfrontend.entity.Book] and content type [application/json;charset=UTF-8]; nested exception is org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Unrecognized token 'Book': was expecting (JSON String, Number, Array, Object or token 'null', 'true' or 'false'); nested exception is com.fasterxml.jackson.core.JsonParseException: Unrecognized token 'Book': was expecting (JSON String, Number, Array, Object or token 'null', 'true' or 'false')...

Can anyone help me for this or is there any special way to send form data to saver side?

0 Answers
Related