Spring Rest Service Post request error - java

It may be a basic question related to Spring Rest service Post request
Below is my Controller mapping code:
#RequestMapping(value = "test", method = RequestMethod.POST)
#ResponseBody
public String addFruits(#RequestBody RequestWrapper fruits) {
// ...
System.out.println("test");
return null;
}
Below is the RequestWrapper class:
public class RequestWrapper{
List<String> ids;
String languageCode;
...
}
Now if in advanced Chrome rest client, with content-type as application/json
if I post the following request :
["ids": [{ "1","2","3","4"}]
,
"languageCode" : "en_US"
]
I get the following error:
Error 400: SRVE0295E: Error reported: 400
Any clue as to where I am going wrong?

The issue was due to an incorrect JSON format in the actual question.
With due help from Soitirios Delimanolis and Alejandro Agapito Bautista could correct the json format and the code worked.
The correct json format is:
{ "ids": [ 1, 2, 3, 4 ], "languageCode": "en_US" }
Also learnt from Alejandro Agapito Bautista's the json validation link
jsonlint.com

Related

Unable to subscribe web-hook for SharePoint online

We are unable to subscribe web-hook for SharePoint online from our Spring-Boot application.
Providing valid notification URL(https enabled, publicly accessible, valid domain name, Post method) as parameter while consuming rest API in order to subscribe web-hook.
#PostMapping(value = "/spnotification")
#ResponseBody
public ResponseEntity<String> handleSPValidation(#RequestParam final String validationtoken) {
LOG.info("validationToken : " + validationtoken);
return ResponseEntity.ok().contentType(MediaType.TEXT_PLAIN)
.body(validationtoken);
}
And on this notification URL end-point, we are able to receive validation string from share-point as parameter and same string we are retiring in less then 5 sec with content-type text/plain and http status code 200 as response.
still getting 400 bad request with below error message.
400 Bad Request: [{"error":{"code":"-1, System.InvalidOperationException","message":{"lang":"en-US","value":"Failed to validate the notification URL 'https://example.com/notification-listener-service/api/webhook/spnotification'."}}}]
Note : We are following this API documentation to subscribe web-hook.
We tried Graph API also for the same purpose but in that case getting below error.
"error": {
"code": "InvalidRequest",
"message": "The server committed a protocol violation. Section=ResponseHeader Detail=CR must be followed by LF"
}
Please find this diagram for more understanding on this issue.
We really appreciate if someone can help us on the same.
Please check the #PostMapping(value = "/notification", headers = { "content-type=text/plain" })
#PostMapping(value = "/notification", headers = { "content-type=text/plain" })
#ResponseBody
public ResponseEntity<String> handleSPValidation(#RequestParam final String validationtoken) {
LOG.info("validationToken : " + validationtoken);
return ResponseEntity.ok().contentType(MediaType.TEXT_PLAIN)
.body(validationtoken);
}
GitHub Code

IBM MobileFirst Adapter accepting Multipart request

I am a newbie to IBM MobileFirst, I am trying to upload an image using Multipart. Whenever I try to call the API to upload image I get an error in the Postman saying 415 content not found or 500 server error. So I just wanted to know does IBM mobile first java adapter accepts multi-part requests?
I have attached the Java code used , but none of these are working:
1)
#RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
public #ResponseBody
String uploadFileHandler(#RequestParam("file") MultipartFile file)
{
return null;
}
tried this also :
#POST
#Path("/upload")
#Produces(MediaType.APPLICATION_JSON)
#Consumes(MediaType.APPLICATION_JSON)
#OAuthSecurity(enabled=false)
public ResponseEntity<?> upload(#RequestParam("files") MultipartFile files) {
log.info("XXXXXXXXXXXXXXXXXXXX");
return null;
}
#POST
#Path("/addEmployeeAttachment")
#Produces(MediaType.APPLICATION_JSON)
#Consumes(MediaType.MULTIPART_FORM_DATA)
#OAuthSecurity(enabled=false)
public #ResponseBody Map<String, Object> addEmployeeAttachment(
#RequestParam(required = false, value = "attachmentFile") MultipartFile attachmentFile) {
log.info("xxxxxxxxxx");
return null;
}
With reference to IBM Mobile first development reference document https://www.ibm.com/support/knowledgecenter/SSHS8R_8.0.0/com.ibm.worklight.apiref.doc/apiref/c_restapi_oview.html
We can use Deploy (POST) for Deploys a multipart compressed file.
JSON example:-
{
"ok" : false,
"productVersion" : "8.0",
"transaction" : {
"appServerId" : "Tomcat",
"description" : {
"name" : "myname",
"type" : "mytype",
},
"errors" : [
{
"details" : "An internal error occured.",
},
...
],
"id" : 1,
"project" : {
"name" : "myproject",
},
"status" : "FAILURE",
"timeCreated" : "2014-04-13T00:18:36.979Z",
"timeUpdated" : "2014-04-14T00:18:36.979Z",
"type" : "UPLOAD_ARTIFACT",
"userName" : "demouser",
},
}
Standard Error code:-
Errors 400 No deployable data is provided. 403 The user is not
authorized to call this service. 404 The corresponding runtime is not
found or not running. 500 An internal error occurred.
Could you pleas refer How can I make a multipart/form-data POST request using Java? as well.
I hope it will help you to understand more about multipart API.

Webhook to collect a JSON: Request method POST not supported

I'm writing a controller with Java for a webhook URL that receives a POST method call, with a JSON body, that I need to collect.
This is a simplified version of the controller, with Spring annotations:
#RestController
public class MyWebhoook {
#PostMapping("/my-webhook")
public void getMyJson(#RequestBody Map<String, Object> json) {
System.out.println("WebHook collected JSON: " + json);
}
}
I test it with Postman sending this JSON:
Header: Content-Type / application/json
{
"webhookKey" : "tranviaVermellCostaAvall",
"token" : "xx",
"channelId": 1,
"propertyId": "999999",
"status": "new",
"reservationId": "111211221",
"reservationStatus" : 1
}
And I get this answer:
{
"timestamp": "2019-04-09T07:23:38.093+0000",
"status": 405,
"error": "Method Not Allowed",
"message": "Request method 'POST' not supported",
"path": "/my-webhook"
}
The server log, gives some more information:
Request method 'POST' not supported, path=/my-webhook}] as "application/json" using [org.springframework.http.converter.json.MappingJackson2HttpMessageConverter#7756c3cd
I've tried those different approaches, with the same result:
#RequestMapping(value = "/my-webhook", produces = MediaType.APPLICATION_JSON_VALUE, method = RequestMethod.POST) instead of the #PostMapping("/my-webhook") annotation.
Modelling the received JSON as a java object instead of the Map<String, Object> json.
Using HttpServletRequest instead of the #RequestBody annotation, trying to read the request as a String.
I do not understand the reason why the POST method is not allowed. Any help, would be very much appreciated.
I added {} between your method and got a 200 as return. I added the pictures below on what code, request and console output i got.
I copied your code to my spring boot app, worked perfectly via postman...
API:
#PostMapping("/my-webhook")
public void getMyJson(#RequestBody Map<String, Object> json) {
System.out.println("WebHook collected JSON: " + json);
}
RequestBody:
{
"webhookKey" : "tranviaVermellCostaAvall",
"token" : "xx",
"channelId": 1,
"propertyId": "999999",
"status": "new",
"reservationId": "111211221",
"reservationStatus" : 1
}
URL: http://localhost:8080/my-webhook
Try to:
Update and Clean your project.
Invalidate IDE cache and restart it, and try again.
The problem was with the CSRF (Cross-site request forgery) security configuration. The path of the webhook, has to be taken out of the CSRF control. Otherwise, the POST request doesn't pass the CSRF control.
This is a simplified extract of the security settings:
#Configuration
#EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter{
#Override
protected void configure(HttpSecurity http)throws Exception{
http
.csrf()
.ignoringAntMatchers("/my/webhook")

Test rest service having RequestParam using postman

I want to test my REST service in order to save a product having a certain category (manyToOne) with Postman:
This is the body of my request:
{
"categoryId": 36,
"product": {
"code": "code1",
"name": "product1",
"price": 20
}
}
And this is how the signature of my REST service method looks like:
#RequestMapping(value = "/addProduct", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<ProductBean> add(#RequestParam(value ="categoryId") Long id, #RequestParam(value = "product") ProductBean productBean)
I put in Postman my URL with the /addProduct at the end, then I choose POST. In the body tab, I choose raw and select the JSON (application json).
When I send the request I got HTTP 400.
How can test this without error in Postman?
Edit
I want to test it using postman to be sure that my REST is working before adding the front part. This is how I will send the data from the front
add: function (product, id, successCallBack, failureCallBack) {
$http({
method: 'POST',
url: "/addProduct",
params: {
product: product,
categoryId: id
},
headers: {'Content-Type': 'application/json'}
}).then(successCallBack, failureCallBack);
}
Your method signature is incorrect. #RequestParam is the parameter in the uri, not the body of the request. It should be:
public ResponseEntity<ProductBean> add(MyBean myBean)
where MyBean has to properties: id and product or
public ResponseEntity<ProductBean> add(#ModelAttribute(value ="categoryId") Long id, #ModelAttribute(value = "product") ProductBean productBean)
For more on mapping requests see Spring documentation
If you want to stick to your original mapping, then everything should be passed in the query string and nothing in the body.
The query string will look something like that:
/addProduction?categoryId=36&product={"code":"code1",...}

Deserializing json array in Spring MVC controller

I am sending a list of json object and trying to deserialize it in my Spring controller. But all the time I am getting error of 'Bad request' and results into a status code of 415. However, my json array is a valid one.
json is -
{
"users": [
{
"userName": "john",
"email": "john#gmail.com",
"user_id": "u223344"
},
{
"userName": "Smith",
"email": "smith#gmail.com",
"user_id": "u223345"
}
]
}
Ajax call is as follows -
$.ajax({
url: $("#addNewUser").attr("action"),
data: JSON.stringify({users : dataToSend}),
dataType: 'json',
type: "POST",
beforeSend: function(xhr) {
xhr.setRequestHeader("Accept", "application/json");
xhr.setRequestHeader("Content-Type", "application/json");
},
success: function(data){
alert('success= ' + data);
},
error:function(data,status,er) {
alert("error: "+ data.responseText +" status: "+status+" er:"+er);
}
});
Wrapper classes are as follows. User and UserWrapper class -
public class User {
private String email;
private String userName;
private String user_id;
//getters and setters
}
public class UserWrapper {
private List<User> userList;
//getter and setter
}
And finally the spring MVC controller is -
#RequestMapping(value="/user/add", method=RequestMethod.POST,
produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE)
#ResponseBody
public void createTeamMember(#RequestBody UserWrapper userWrapper) {
try{
for(User user : userWrapper.getUserList()){
System.out.println(user.getEmail());
}
}catch(Exception ex){
ex.printStackTrace();
}
}
I've added dependency for jackson-core and jackson-mapper in pom.xml. And I am using Spring 4.0.3. Any help is appreciated.
As #shazin is saying, you've most likely posted a wrong method to your question, or if not, simply make a change that he suggested.
You'll need another fix, and that is renaming the usersList property from UserWrapper to users so that it matches the JSON property being sent.
We these fixes, you should not have further problems, since your request is OK.
I think you need to change your #RequestBody POJO to UserWrapper
#RequestMapping(value="/task/add", method=RequestMethod.POST,
produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE)
#ResponseBody
public void createTeamMember(#RequestBody UserWrapper userWrapper) {
// Code to create members
}
I will not suspect server side binding error yet because you are getting 415 - Unsupported Media Type error. You are setting correct media type on controller and hence server side is looking good.
At client side, Please make sure you are using jquery 1.5+ to make sure beforeSend() method is getting invoked.
Easier way to content type will be,
$.ajax({
url:api,
....
contentType: "application/json"
});
Please inspect network request from browser and make sure content type is set in header.
If you receive 400-Bad Request, then you can start looking deserializing issues.

Categories