415 error when sending POST request to REST API - java

I'm developping a REST API in JavaEE and a client using this API in ReactJS.
The API works perfectly when I'm using postman, but as soon as I use fetch method in JS to POST JSON information through my client, I'm getting a 415 error: Unsupported Mediatype in my browser's console.
For the API, I'm using Jersey to process requests and Hibernate as ORM. I have genson dependency and as I said, everythig works perfectly fine with Postman.
I also checked the result of JSON.stringify() before sending it and it looks fine to me.
Plus, in my server's console, I'm getting this error everytime I try to POST anything :
GRAVE: A message body reader for Java class model.User, and Java type class model.User, and MIME media type application/octet-stream was not found.
I checked and double-checked everything, I'm sending the right headers, the browser identifies the request as 'application/json' content type but it's like my API still doesn't accept it, or receives it as application/octet-stream mediatype.
Here is the method where fetch is done :
signIn(){
console.log(JSON.stringify(this.state));
fetch('http://localhost:8080/P52/users', {
method: 'POST',
body: JSON.stringify(this.state),
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
}).then(res => {
return res.json();
}).catch(err=>err)
}
The method that receives data in the API :
#POST
#Consumes(MediaType.APPLICATION_JSON)
public User createUser(User u){
return UserController.createUser(u);
}
The controller just create a new instance of User class to run this code in the User model class :
public User(User u){
this.id = u.getId();
this.pseudo = u.getPseudo();
this.firstname = u.getFirstname();
this.lastname = u.getLastname();
Session session = (Session)HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
session.save(this);
session.getTransaction().commit();
session.close();
}
If anyone has the answer to my problem or has already faced it, please let me know so I can finally move forward with this project.
Thank you in advance,
Arthur

415 is Unsupported Media Type (https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/415)
try changing
#Consumes(MediaType.APPLICATION_JSON)
to
#Consumes(MediaType.APPLICATION_JSON_VALUE)

Related

Spring app returning HTTP 415 Unsupported Media Type

I'm making SpringMVC webapp. I have a Controller:
#RestController
#RequestMapping(value ="/certificate", produces = MediaType.APPLICATION_JSON_VALUE)
public class GiftCertificateController {
private final GiftCertificateService gcs;
#Autowired
public GiftCertificateController(GiftCertificateService gcs) {
this.gcs = gcs;
}
#PostMapping
public ResponseEntity<?> createCertificate(#RequestBody GiftCertificate gc) throws Exception {
gcs.createCertificate(gc);
return new ResponseEntity<>(Map.of("status", HttpStatus.CREATED), HttpStatus.CREATED);
}
// some GetMapping and DeleteMapping functions
// omitted for simplicity
}
And I am trying to make a POST in Postman to create a certificate with JSON:
{
"name": "sas",
"description": "sasasas",
"price": 12,
"duration": 12
}
I tried to change my Content-type to application/json, but it still isn't work.
The request is not being handled by your controller. HTTP 415 means "Unsupported Media Type".
The HTTP 415 Unsupported Media Type client error response code indicates that the server refuses to accept the request because the payload format is in an unsupported format.
The format problem might be due to the request's indicated Content-Type or Content-Encoding, or as a result of inspecting the data directly.
Try adding the header "Content-Type" with value "application/json" to your postman request.
The search engine in Stack Overflow is quite powerful. These questions might also provide helpful info:
POST JSON fails with 415 Unsupported media type, Spring 3 mvc
Http 415 Unsupported Media type error with JSON
415--Unsupported Media Type in Spring
​​The error 415-The unsupported file format error occurs when server refuses to accept the request because the payload format is in an unsupported format of file type.
1.Ensure that you are sending the proper Content-Type header value.
2.Verify that your server is able to process the value defined in the Content-Type header.
3.Check the Accept header to verify what the server is actually willing to process.
To resolve this issue, explicitly set the content type under the request headers as Post
Make sure to change body "Text" to "JSON"
I have also faced the issue even after changing the Content-type to application/JSON
to resolve it I have created a DTO to take the input from the JSON file
and then passed the values to the entity object through the DTO

Getting a 400 Bad Request when Angular HttpClient posts a Set<> to a SpringBoot endpoint

I am exposing an endpoint that accepts a Set<> as a #RequestBody this way :
public #ResponseBody ResponseEntity<Response> addTeamOwner(#RequestParam("teamName") String teamName, #RequestBody Set<String> emails, HttpServletRequest request){...}
And my Angular frontend is calling this endpoint like this :
let params = new HttpParams().set('teamName', teamName);
let url = `${UrlManager.TEAMS}/addOwners?${params.toString()}`;
this.httpClient.post<any>(url, emails);
For some reason I'm getting 400 Bad Request : HttpErrorResponse {headers: HttpHeaders, status: 400, statusText: 'Bad Request', url: 'http://localhost:4200/api/teams/addOwners?teamName=DEMO_TEAM', ok: false, …}
It seems that the Set that Angular is sending is not accepted by the backend because when I change to an Array everything works fine !
FYI, my API is SpringBoot and my frontend is Angular.
Actually it is not possible to serialize data sent within Set because the data are not stored as properties.
The solution was to convert the set to an array this way :
this.httpClient.post<any>(url, [...emails]);
and the backend is able to deserialize it as a Set correctly.

Spring Controller GET/POST/PUT to another interface

I am using React as frontend and Java Spring Boot as backend.
React sends JSON form data as GET/PUT/POST requests to my backend url (http://localhost:8080/test). Now, I wan't to send this JSON forward to another interfaces GET endpoint (https://another/interface/add?id={id}). This interface then queries database based on the id and answers 200 OK message with a JSON reply which I need to display (send back to frontend).
1. What is the correct way of sending a request to another interface from Spring Boot backend? In the same method I catched the frontends data?
2. I also have to set HTTP headers to the GET request, how would I go on about this?
Example of how Frontend is sending an id field as a JSON to backend:
React POST
addId = async (data) => {
return this.post(/localhost:8080/test/id, data)
}
Example of how Backend is receiving the id field:
Spring Boot POST
#PostMapping("test/id")
public String test(#RequestBody String id) {
return id;
}
As I understand you want to get data from backend with json body and httpstatuscode 200 . Am i right?
May be you can try this
#GetMapping(/interface/add)
public ResponseEntity<?> test(#RequestParam("id") String id){
//write code you want
return ResponseEntity.status(HttpStatus.OK).body("string" or dto possible);
}
ResponseEntity send body with httpstatus code and if you want to send requestparam you set #RequestParam annotation to set .
When I do project with springboot and react. I use json type to exchange data. And Most Services usually exchange data with json data type.
2.I confused about this Question if you send data React to springboot your code is right
Axios.get("localhost....", data) you can change http type with
Axios.(get, post, delete)

POST doesn't work Spring java

I have an web application and I'm trying to creat a simple POSt method that will have a value inside the body request:
#RequestMapping(value = "/cachettl", method = RequestMethod.POST)
#CrossOrigin(origins = "http://localhost:3000")
public #ResponseBody String updateTtl(#RequestBody long ttl) {
/////Code
}
My request which I call from some rest client is:
POST
http://localhost:8080/cachettl
Body:
{
"ttl": 5
}
In the response I get 403 error "THE TYPE OF THE RESPONSE BODY IS UNKNOWN
The server did not provide the mandatory "Content-type" header."
Why is that happening? I mention that other GET requests are working perfectly.
Thanks!
Edit:
When I tried it with postman the error message I got is "Invalid CORS request".
Spring application just doesn't know how to parse your message's body.
You should provide "header" for your POST request to tell Spring how to parse it.
"Content-type: application/json" in your case.
You can read more about http methods here: https://developer.mozilla.org/en-US/docs/Learn/HTML/Forms/Sending_and_retrieving_form_data
Updated:
Just in case of debug, remove useless annotations to test only POST mechanism. Also, change types of arg and return type. And try to use case-sensitive header.
#RequestMapping(value = "/cachettl", method = RequestMethod.POST)
public void updateTtl(#RequestBody String ttl) {
System.out.println("i'm working");
}
Since the error is about the response type, you should consider adding a produces attribute, i.e :
#RequestMapping(value = "/cachettl", method = RequestMethod.POST, produces=MediaType.APPLICATION_JSON_VALUE)
Since you are also consuming JSON, adding a consumes attribute won't hurt either :
#RequestMapping(value = "/cachettl", method = RequestMethod.POST, consumes=MediaType.APPLICATION_JSON_VALUE, produces=MediaType.APPLICATION_JSON_VALUE)
The error message is slightly misleading. Your server code is not being hit due an authentication error.
Since you say spring-security is not in play then I suspect you're being bounced by a CORS violation maybe due to a request method restriction. The response body generated by this failure (if any at all) is automatic and will not be of the application/json type hence the client failure. I suspect if you hit the endpoint with something that doesn't care for CORS such as curl then it will work.
Does your browser REST client allow you to introspect the CORS preflight requests to see what it's asking for?

What is format from url in AJAX to send POST method with RESPONSE ENTITY

I already search tutorial in spring for method POST, insert the data with response entity (without query) and I getting error in ajax. I want to confirm, What is format url from ajax to java? below my assumption:
localhost:8080/name-project/insert?id=1&name=bobby
is the above url is correct? because I failed with this url. the parameter is id and name.
mycontroller:
#PostMapping(value={"/insertuser"}, consumes={"application/json"})
#ResponseStatus(HttpStatus.OK)
public ResponseEntity<?> insertUser(#RequestBody UserEntity user) throws Exception {
Map result = new HashMap();
userService.insertTabelUser(user);
return new ResponseEntity<>(result, HttpStatus.CREATED);
}
my daoimpl:
#Transactional
public String insertUser(UserEntity user) {
return (String) this.sessionFactory.getCurrentSession().save(user);
}
the code running in swagger (plugin maven) but not run in postman with above url.
Thanks.
Bobby
I'm not sure, but it seems that you try to pass data via get params (id=1&name=bobby), but using POST http method implies to pass data inside body of http request (in get params, as you did, data is passed in GET method) . So you have to serialize your user data on client side and add this serialized data to request body and sent it to localhost:8080/name-project/insert.
As above answer suggest. You are trying to pass data as query parameters.but you are not reading those values in your rest API.either you need to read those query parameters in your API and then form an object or try to pass a json serialized object to your Post api as recommendation. Hope it helps.

Categories

Resources