Trouble sending multipart request - java

I'm creating a new endpoint to upload and process excel and csv files.
I'm trying to create an endpoint using springs Multipart upload, but I cannot reach the endpoint from Postman or using curl in command line.
I have a RestController
#RestController
#RequestMapping("/v1/finance/ratecard")
public class RateCardController
and I am able to access other endpoints in this controller without a problem.
I added new endpoint to this controller.
#PostMapping(value = "/uploadFile")
#ResponseStatus(HttpStatus.OK)
public void uploadExcelFile(#RequestPart("file") MultipartFile file, #RequestPart("meta-data") UploadRateCardRequest uploadRateCardRequest) {
//Unrelated logic here
}
And I'm trying to send POST request using postman, I haven't touched Content-Type header, it's generated by Postman, but I have had no success reaching it. I always get 404 error. Postman Config
I have tried adding consumes = "multipart/mixed" and "multipart/form-data" to #PostMapping annotation, but those changes had no effect.
What am I doing wrong? Am I missing some obvious request parameter in Postman, or is my controller set up wrong?

I had problems in uploadExcelFile method, one of dependencies I was using could not detect valid beans for an autowired interface. That was causing this issue.
Nothing was wrong with Controller set up or postman config pictured in the post.

Related

How to get and image that my Spring boot API returns as FileSystemResource

I have a spring boot application deployed on a tomcat that's make me able to upload images from and android application. Now I'm trying to get that images. The problem is that my endpoint of my controller returns a FileSystemResource and I don't know how to handle it.
Endpoint:
#GetMapping(value = "/getFotoPerfil", produces = MediaType.IMAGE_JPEG_VALUE)
public FileSystemResource getFotoPerfil(#RequestParam("path") String path) {
return utilitiesService.findInFileSystem(path);
}
The response I receive:
If I make the call with Postman, it works:
Any help will be appreciated
Your problem is that your client code seems to be assuming that it will be getting JSON. The controller is returning an image (although it's a PNG, even though you're inaccurately telling the client it's image/jpeg), which is binary data. In Java, this response should normally be handled as a byte[] instead of a String.

Spring with Tomcat 7: PUT request returns 403 for strange resons

I have a web application written on Spring 3.1 (not boot) and running on Tomcat 7.
I have a #Controller implements method PUT on a certain URL.
In some cases When sending a PUT request from Postman, I get a 403 response instead of what is expected.
For example:
Sending the request to a non-implemented URL (on GET to the same URL I get a 404)
Sending an invalid JSON as the request body (Expected 400)
Sending a string instead of a numeric request parameter (Expected 400)
I also implement a filter that excepts all requests and just before the filter exists, I can verify I get the expected status from the rest of the chain.
This is an example of a controller code:
#RequestMapping(value = "/{book}", method = RequestMethod.PUT)
#ResponseStatus(HttpStatus.OK)
#ResponseBody
protected Book put(#PathVariable(value = "bookId") String id, #RequestBody #Valid Book book) {
return book; // just a stub
}
And this is the relevant part in the filter:
filterChain.doFilter(req, res);
// res.getStatus() is the expected status
return; // after this line I move to internal code of Tomcat which I cannot debug, but something happens there.
What do I miss?
Thanks
Check out CORS filter configuration first as Andreas said: https://tomcat.apache.org/tomcat-8.5-doc/config/filter.html
Check out this flowchart also https://tomcat.apache.org/tomcat-8.5-doc/images/cors-flowchart.png
Check out this stackoverflow post finally 403 on JSON PUT request to Tomcat with Spring 3.0.5 and Jackson
Your path variable value is bookId, but your url uses {book}; both should match. Try changing the url to "/{bookId}" or the path variable to #PathVariable(value = "book"). It might be useful to know the URL that you are calling to help analyse the issue.

ResponseEntity body lost between two webservice calls

I have a webservice which calls another WS and returns the response from the second WS. It looks like so:
// MyController
public ResponseEntity<Foo> requestFooController(#RequestBody #Valid Bar request) {
return this.myService.requestFooService(request);
}
//MyService
ResponseEntity<Foo> requestFooService(Bar request) {
Buzz improvedRequest = ...
return this.secondWS.secondRequestFoo(improvedRequest);
}
When I call the API through Postman, I receive a HTTP OK response with an empty body. Yet, when I'm in debug mode I can see that the service is returning a ResponseEntity with a body. The headers are not lost though.
I changed my code like so and it works fine:
// MyController
public ResponseEntity<Foo> requestFooController(#RequestBody #Valid Bar request) {
ResponseEntity<Foo> tmp = this.myService.requestFooService(request);
return ResponseEntity.status(tmp.getStatusCode()).body(tmp.getBody());
}
Now through Postman I do have the expected body. However, I don't understand the behaviour. I thought that maybe it's due to the fact that the body is some kind of stream that can be read once or something similar. But from reading the source code I don't see anything that could explain this behaviour.
I'm using the Netflix-stack (so HTTP calls between the two WS are made through a Feign client).
Any idea why I'm getting this result?
EDIT:
More details on my stask:
SpringBoot 1.5.3.RELEASE
Feign 2.0.5
There is a bug that causes the named body of an HTTP MultiPart POST to fail. The symptom of this is that you make a POST request with a body, and Spring-Boot can't match it up to an endoint. The exception I see is:
2019-01-23 15:22:45.046 DEBUG 1639 --- [io-8080-exec-10] .w.s.m.m.a.ServletInvocableHandlerMethod : Failed to resolve argument 3 of type 'org.springframework.web.multipart.MultipartFile'
org.springframework.web.multipart.support.MissingServletRequestPartException: Required request part 'file' is not present
Zuul is doing caching of the request in order to re-try multiple times. In this process, it fails to preserve the named field for the binary body. You may find it working if you preface the request with zuul. So instead of http://myserver.com/myservice/endpoint use zuul in the path: http://myserver.com/zuul/myservice/endpoint
That will effectively avoid the saving of the request and the retry mechanism.
More details are available on this issue in Zuul's GitHub Bug List.

Java Spring Restcontroller Post

I need help creating a POST request to my Java Spring Restcontroller.
This is my controller -
#RestController
#RequestMapping("hedgesimulator/")
public class HedgeSimulatorController {
#RequestMapping(value = "hedgesim/", method = RequestMethod.POST)
#ResponseBody
public HedgeSimulatorLog putHedgeSimulation(
#RequestBody HedgeSimulatorLog hedgeSimulatorLog) {
System.out.println(hedgeSimulatorLog.toJsonString());
return hedgeSimulatorLog;
}
}
I am using Chrome's "Advanced Rest Client" Plugin to POST my request to my URL (I am sure my localhost is running properly, etc.)
What do I need to add to my header?
I receive an error for "HTTP 400 - Status report: The request sent by the client was syntactically incorrect"
Please help!
To pass an object to controller you must configure HttpMessageConverter which helds serialization and deserealization of this object. For example, if you want to pass an object to controller as JSON, set a MappingJackson2HttpMessageConverter as parameter in your mvc declaration in spring config file.
<mvc:annotation-driven>
<mvc:message-converters>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/>
</mvc:message-converters>
</mvc:annotation-driven>
If http message converter configured properly, maybe request was improperly formed.
#RequestMapping(value = "/hedgesim/", method = RequestMethod.POST)
Try with following, hope you might resolve the issue:
Since you are using #RestController annotation, so no need to use #ResponseBody annotation again, which is redundant.
If you are using spring boot, then make sure you have added the below dependency .
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
If the project is not spring boot, then add dependency for jackson : com.fasterxml.jackson.databind.ObjectMapper
Just to make sure the request body is correct, what you can do is, execute request method first, get the JSON response, pass the same JSON for POST, so this might avoid some typo/human error while creating JSON data.
Hope, it helps.
You can do the following checks.
Validate the request body you are sending through some online tool like
JSonLint.
Check whether MappingJackson2HttpMessageConverter is registered or not. By default, Spring registers this converter if you have the jar in the classpath.
No need to use #ResponseBody if you are using #RestController. So remove it.
For a complete example on creating and consuming REST Service using Spring 4.0, you can visit Techno Spots.

Post request to Jersey from Laravel

I have a simple REST API created with Jersey on Glassfish server.
On the other hand, I have a Laravel application that uses this API. Now, I have several GET routes on Jersey app, and this works with no problem. I used it with curl and everything went well.
At the end, I have one post request that I should send. Form consists of about 50 fields, and I'm not sure how to triger it.
When I put the url to post method into form action attribute, I get this message
HTTP Status 415 - Unsupported Media Type
I have tried with
#Consumes(MediaType.APPLICATION_FORM_URLENCODED)
And with
#Consumes(MediaType.APPLICATION_JSON)
And I get the same error with both
I haven't done this but it, but be sure to include the form parameters in the method signature
#POST
#Consumes("application/x-www-form-urlencoded")
public void post(#FormParam("name") String name) {
// Store the message
}
as described here

Categories