**I am trying to make a POST controller in springboot having request parameter as JSON object and hiting the controller from the postman .The problem I am facing is that I want to pass a JSONObject in the parameter itself from the postman. I am sending JSON from POSTMAN in body, basically pasted JSON object in the raw body **
#RestController
public class PostController {
#PostMapping(value="/status")
public JSONObject status (#RequestBody JSONObject jsonObject){
System.out.println(jsonObject.toString());
return jsonObject;
}
}
`
I am hitting from the postman with POST request at the url : localhost:8080/status ,,
I am not getting the appropriate response. Main problem is that the JSON object is not getting passed to the request . PLease explain.
Intellij terminal response :
{}
AT line 19
and POSTMAN response is :
{
"empty": true,
"mapType": "java.util.HashMap"
}
enter image description here
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.
I have an issue in Spring Boot with Kotlin
I have a function that accepts all major Content Types as defined below:
#PostMapping(
value = ["/users/new"],
consumes = [
MediaType.APPLICATION_JSON_VALUE,
MediaType.APPLICATION_XML_VALUE,
MediaType.MULTIPART_FORM_DATA_VALUE,
MediaType.APPLICATION_FORM_URLENCODED_VALUE]
)
fun registerNewUser(
#RequestHeader("X-Forward-For") ipAddress: String?,
newUser: NewUser,
request: HttpServletRequest
): ResponseEntity<ObjectNode> {
var realIPAddress = ipAddress
if (realIPAddress == null) {
realIPAddress = request.remoteAddr
}
return userService.registerUser(realIPAddress!!, newUser)
}
Here is how my NewUser class is defined in kotlin
data class NewUser(val email: String?, val password: String?)
Here is how I am doing the check in the registration function
if (!StringUtils.hasText(newUser.email)) {
return responseHandler.errorResponse(
HttpStatus.BAD_REQUEST,
"Please provide an email address"
)
}
Now when I sent a post request with postman and even axios I keep getting the error as shown in the screenshot below
That error message should only be displayed if email address is not provided. But as you can see clearly, the email address is provided in the JSON Payload.
What could be wrong?
Note: This works when the Content-Type is application/x-www-form-urlencoded but doesn't work when the Content-Type is application/json
put #RequestBody before newUser parameter to specify that input should be inside http body part. by default function parameters in spring are considered to be url parameters which can be further clarified with #RequestParam.
there are 2 ways to insert request parameters into http request. one is to attach request parameters to end of the url and the other is to put in http body with application/x-www-form-urlencoded as the content-type.
I have a Spring App witch use a controller like this:
#PutMapping("/block/{blockid}/service/{serviceid}")
public ResponseEntity<String> config(#PathVariable blockid, #PathVariable serviceid, #RequestBody String body) {
{
And I using Postman to test the request, if i send this request to this url:
url: localhost:7000/block/myBlockTest/service/externalServiceTest[0]
Response this error:
Description The server cannot or will not process the
request due to something that is perceived to be a client error
(e.g., malformed request syntax, invalid request message framing, or
deceptive request routing).
I know the problem is "[0]" in the url.
Is there any way I can send this in the URL ?
Thanks.
OK, I just need modify the request to be localhost:7000/block/myBlockTest/service/externalServiceTest%5B0%5D
Special parameters.
https://cachefly.zendesk.com/hc/en-us/articles/215068626-How-to-format-URLs-that-have-special-characters-in-the-filename-
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.