Content type 'text/plain;charset=UTF-8' not supported error in spring boot inside RestController class - spring

I got the following #RestController inside a spring boot application :
#Data
#RestController
public class Hello {
#Autowired
private ResturantExpensesRepo repo;
#RequestMapping(value = "/expenses/restaurants",method = RequestMethod.POST,consumes =MediaType.APPLICATION_JSON_VALUE ,
headers = MediaType.APPLICATION_JSON_VALUE)
#ResponseBody
public void hello(#RequestBody ResturantExpenseDto dto)
{
Logger logger = LoggerFactory.getLogger("a");
logger.info("got a request");
ResturantExpenseEntity resturantExpenseEntity = new ResturantExpenseEntity();
resturantExpenseEntity.setDate(new Date(System.currentTimeMillis()));
resturantExpenseEntity.setName(dto.getName());
resturantExpenseEntity.setExpense(dto.getExpense());
repo.save(resturantExpenseEntity);
}
}
When I try to send request from restClient/RestedClient (both addons of mozila) I get the following error :
{
"timestamp": 1512129442019,
"status": 415,
"error": "Unsupported Media Type",
"message": "Content type 'text/plain;charset=UTF-8' not supported",
"path": "/expenses/restaurants"
}
This eror states that the end point doesnt support Json content,But I did
put
consumes =MediaType.APPLICATION_JSON_VALUE
inside #RequestMapping annotation
What am I missing?

Late response but I had the same problem posting the answer it might be useful to someone so I installed Postman and then just change your Content-Type to application/json

If the request is made like this: then it will resolve the issue.
curl -X PUT -H 'Content-Type: application/json' -i http://localhost:8080/spring-rest/api/employees/500 --data '{
"name": "abc",
"email": "abc.a#gmail.com",
"salary": 10000
}'
I see the headers are proper: headers = MediaType.APPLICATION_JSON_VALUE
but when the request is made, at that time we need to inform the handler that its a application/json mime type.

This is late too, but in RESTClient(Mozilla addon), you can add Content-Type: application/JSON from the Headers dropdown menu and even at the response side change it to JSON format

if you are using html with ajax.Check the request header and the payload. Make sure the ajax has the following fields
url : your url
type : 'post',
dataType: "json",
contentType: "application/json; charset=utf-8",
data : JSON.stringify( your payload )
if the ajax call has the following fields remove them and try again
processData : false,
contentType : false,

Related

application/json not supported when passing multipart files and json together

I have a REST controller method which will take multipart files and JSON object to save as a product with images.
Here is my controller method.
#PostMapping(value = "/{username}/saveProduct", consumes = {MediaType.APPLICATION_JSON_VALUE, MediaType.MULTIPART_FORM_DATA_VALUE, MediaType.APPLICATION_OCTET_STREAM_VALUE})
public void saveProduct(#PathVariable("username") String username,
#RequestPart("multipartFiles") List<MultipartFile> multipartFiles,
#RequestPart("product") Product product)
{
Users user = userService.findUserByUsername(username);
List<Images> listOfImages = productService.getBLOBfromFile(multipartFiles, product);
product.setImages(listOfImages);
product.setUser(user);
user.setProducts(product);
userService.saveUser(user);
}
For some reason I am getting this error:
"timestamp": "2021-01-18T20:05:32.409+00:00",
"status": 415,
"error": "Unsupported Media Type",
"trace": "org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/json' not supported\r\n\tat org.
From postman I am sending
I tried using #RequestParam and #ModelAttribute as well. Did not work for me.
Also, this method was working when I was writing MVC app.

Spring post method "Required request body is missing"

#PostMapping(path="/login")
public ResponseEntity<User> loginUser(#RequestBody Map<String, String> userData) throws Exception {
return ResponseEntity.ok(userService.login(userData));
}
I have this method for the login in the UserController. The problem is when i try to make the post request for the login i get this error:
{
"timestamp": "2018-10-24T16:47:04.691+0000",
"status": 400,
"error": "Bad Request",
"message": "Required request body is missing: public org.springframework.http.ResponseEntity<org.scd.model.User> org.scd.controller.UserController.loginUser(java.util.Map<java.lang.String, java.lang.String>) throws java.lang.Exception",
"path": "/users/login"
}
You have to pass that as JSON in your body, if it's a POST request.
I had a similar issue, was getting this error in my Spring Boot service
HttpMessageNotReadableException: Required request body is missing:...
My issue was that, when I was making requests from Postman, the "Content-Length" header was unchecked, so service was not considering the request body.
This is happening because you are not passing a body to you server.
As can I see in your screenshot you are passing email and password as a ResquestParam.
To handle this values, you can do the following:
#PostMapping(path="/login")
public ResponseEntity<User> loginUser(#RequestParam("email") String email, #RequestParam("password") String password) {
//your imp
}
In order to accept an empty body you can use the required param in the RequestBody annotation:
#RequestBody(required = false)
But this will not solve your problem. Receiving as RequestParam will.
If you want to use RequestBody you should pass the email and password in the body.
You need to send data in Body as JSON
{ "email":"email#email.com", "password":"tuffCookie"}
If it's still not working, try adding additional information UTF-8 in Headers.
key : Content-Type
value : application/json; charset=utf-8
For my case, I must adding UTF-8 in Headers.
In my case it was poorly defined JSON that I sent to my REST service.
Attribute that was suppose to be an object, was in my case just string:
Changed from:
"client" = "",
to:
"client" = { ... },
In my case String did not add additional information about value in different format.

How to solve error message "status": 415, "error": "Unsupported Media Type"," for DELETE request in Spring?

I created a Spring Boot application based on Service Components using this tutorial.
My delette request is constructed in the following way:
#RequestMapping(value = "/api/greetings/{id}", method = RequestMethod.DELETE, consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Greeting> deleteGreeting(#PathVariable("id") Long id, #RequestBody Greeting greeting) {
greetingService.delete(id);
return new ResponseEntity<Greeting>(HttpStatus.NO_CONTENT);
}
All the other requests work finally, but if I make the DELETE request in Postman I get the following error:
{
"timestamp": 1519060345434,
"status": 415,
"error": "Unsupported Media Type",
"exception": "org.springframework.web.HttpMediaTypeNotSupportedException",
"message": "Content type 'application/x-www-form-urlencoded' not supported",
"path": "/api/greetings/2"
}
I have checked the following issues, nothing helped (which is no wonder, none of them is issuing the DELETE request:
415 Unsupported MediaType
415 Unsupported MediaType for POST request in spring application
415 Unsupported Media Type in RESTful webservice
Ask
Your controller is expecting application/json as content-type but as the error message displays
"message": "Content type 'application/x-www-form-urlencoded' not supported",
you should change the header in postman to content-type application/json

Unsupported Media Type in postman

I am implementing spring security with oauth2 and jwt.
the below is my login function
function doLogin(loginData) {
$.ajax({
url : back+"/auth/secret",
type : "POST",
data : JSON.stringify(loginData),
contentType : "application/json; charset=utf-8",
dataType : "json",
async : false,
success : function(data, textStatus, jqXHR) {
setJwtToken(data.token);
},
error : function(jqXHR, textStatus, errorThrown) {
alert("an unexpected error occured: " + errorThrown);
window.location.href= back+'/login_page.html';
}
});
}
And down I have the Controller
#RequestMapping(value = "auth/secret", method = RequestMethod.POST)
public ResponseEntity<?> createAuthenticationToken(#RequestBody JwtAuthenticationRequest authenticationRequest, Device device) throws AuthenticationException {
System.out.println();
logger.info("authentication request : " + authenticationRequest.getUsername() + " " + authenticationRequest.getPassword());
// Perform the security
System.out.println( authenticationRequest.getUsername()+"is the username and "+authenticationRequest.getPassword());
final Authentication authentication = authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(
authenticationRequest.getUsername(),
authenticationRequest.getPassword()
)
);
SecurityContextHolder.getContext().setAuthentication(authentication);
logger.info("authentication passed");
// Reload password post-security so we can generate token
final UserDetails userDetails = userDetailsService.loadUserByUsername(authenticationRequest.getUsername());
final String token = jwtTokenUtil.generateToken(userDetails, device);
logger.info("token " + token);
// Return the token
return ResponseEntity.ok(new JwtAuthenticationResponse(token));
}
But when I try the post request with the postman it shows me
{
"timestamp": 1488973010828,
"status": 415,
"error": "Unsupported Media Type",
"exception": "org.springframework.web.HttpMediaTypeNotSupportedException",
"message": "Content type 'multipart/form-data;boundary=----WebKitFormBoundaryY4KgeeQ9ONtKpvkQ;charset=UTF-8' not supported",
"path": "/TaxiVis/auth/secret"
}
But when I do cosole.log(data) in the ajax call it prints the token?I could not figure out what is wrong.Any help is appreciated.
You need to set the content-type in postman as JSON (application/json).
Go to the body inside your POST request, there you will find the raw option.
Right next to it, there will be a drop down, select JSON (application.json).
Http 415 Media Unsupported is responded back only when the content type header you are providing is not supported by the application.
With POSTMAN, the Content-type header you are sending is Content type 'multipart/form-data not application/json. While in the ajax code you are setting it correctly to application/json. Pass the correct Content-type header in POSTMAN and it will work.
I also got this error .I was using Text inside body after changing to XML(text/xml) , got result as expected.
If your request is XML Request use XML(text/xml).
If your request is JSON Request use JSON(application/json)
If you are still failing with Unsupported Media Type in postman
when calling a SOAP endpoint you could try:
Content-Type: application/soap+xml
i was also having a similar issue. in my case i made two changes
Click on headers tag and add a key 'Content-Type' with Value 'application/json'
Second step is to click on Body tab and select 'raw' radio button and select type as 'JSON' from dropdown as shown below
I had this problem. I had authentication on the authentication tab set up to pass credentials in body.
This error occurred for me when I had the Body set to None.
So I needed an empty body in postman, set to raw JSON to allow this to work even though my main request was parameters in the querystring.
{
}
When this was happening with me in XML;
I just changed "application/XML" to be "text/XML",
which solved my problem.

ExtJS uploading file results in Bad Request error: Required MultipartFile parameter 'file' is not present

I have seen fair amount of threads regarding bad request errors upon file upload, however unlike for others, I am sure that Spring is not at fault here, as I am able to upload file via curl without an issue: curl -X POST -v http://localhost:8080/rest/datasets/ -T test.xlsx
ExtJS uploader:
{
xtype: 'filefield',
fieldLabel: 'Select file',
name: 'file',
fieldName : 'file',
listeners: {
change: function(filefield, value, eOpts) {
var form = filefield.up('form').getForm();
form.submit({
url: '/rest/datasets',
headers : {
'Accept' : '*/*',
'Content-Type' : 'multipart/form-data'
},
waitMsg: 'Uploading'
});
}
}
}
Spring controller
#RestController
#RequestMapping("rest/datasets")
public class DatasetController {
#RequestMapping(method = RequestMethod.POST)
public String uploadFile(
#RequestParam("file") MultipartFile file) {
...
}
}
I am using ExtJS 6.0.1 and Spring Boot 1.3.3
I don't believe it's ExtJS at fault here. I checked your sample in sencha fiddle, and it seems that parameter "file" does exist when posting.
------WebKitFormBoundaryCL4R6o6o2MXXQcAx
Content-Disposition: form-data; name="file"; filename="Capture1.PNG"
Content-Type: image/png
------WebKitFormBoundaryCL4R6o6o2MXXQcAx--
You could also try: Spring mvc: HTTP Status 400 - Required MultipartFile parameter 'file' is not present

Resources