I have this method right now:
#RequestMapping(path = "/api2/rep/report_payment_grouped/{startDate}/{endDate}", method = RequestMethod.GET)
public #ResponseBody
ResponseEntity getPaymentsGroupedReport(HttpServletRequest request,
#PathVariable String startDate,
#PathVariable String endDate,
#RequestParam(required = false, value = "requestId") Integer requestId) {
This returns an object Report with two list, fieldsDefs, data, and the requestId received in the original request:
return ResponseEntity
.ok(new Report(fieldDefs, data, requestId));
This is the returned object client side(it's correct):
In the network data:
Now, the exact same request when the service is deployed in my AWS server, requestId is always null:
This is the response:
I have tried manually setting the requestId serverSide and the value is returned correctly in that case. So it's confirmed that requestId parameter is being received as null/empty.
I suspect your service on AWS isn't able to access the database. Have you looked at the error logs?
Related
I have an endpoint where it supposes to sends a string as a response. My question is do I need to use to response Entity to send string response or just return the string to the consumer?
#GetMapping(value = "/word")
public String getWord() {
String response = "webservice";
return response;
}
Second approach:
#GetMapping(value = "/word", produces ={MediaType.APPLICATION_JSON_VALUE})
public ResponseEntity<String> getWord() {
String response = "webservice";
return new ResponseEntity<>(response, HttpStatus.OK);
}
What is the correct approach to send just a string or use response entity?
What is the correct approach to send just a string or use response entity?
The Spring MVC documentation lists a number of types that can be returned from controller methods.
As I previously answered here and here, ResponseEntity<T> represents the entire HTTP response. Besides the body, its API allows you to set headers and a status code to the response.
Returning just a bean instance or a string is fine but doesn't give you much flexibility: In the future, if you need to add a header to the response or modify the status code, for example, you need to change the method return type.
I have a front-end react application, where i make a request to a REST Jax-RS backend server.
Here is the request being sent
deletePost = (post) =>{
return deleter(config.restUrl + `posts/${post}`)
}
Here i get the standart URL for my backend, with a 'deleter' function, which is just a standardized fetch delete method (which has also worked with other entities as well).
Here is my Jax-RS resource:
#DELETE
#Consumes(APPLICATION_JSON)
#Produces(APPLICATION_JSON)
#Path("/{id: [0-9]+}")
public Response deletePost(#HeaderParam("authorization") String token, #PathParam("id") Integer id) throws ResourceNotFoundException, AuthenticationException
{
AuthenticationContext authenticationContext = authenticationFacade.authenticateBearerHeader(token);
Post post = postFacade.delete(authenticationContext, id);
return Response.ok(gson.toJson(PostDTO.basic(post))).build();
}
The problem is that it gives me an error saying that the form is HTML/text:
MessageBodyWriter not found for media type\u003dtext/html, type\u003dclass com.group3.sem3exam.rest.dto.PostDTO, genericType\u003dclass com.group3.sem3exam.rest.dto.PostDTO
Since it's implying that it is the PostDTO that has the error, I went to check the basic method, which converts the entity into a Data Transfer Object, to be posted back to the client side.
public static PostDTO basic(Post post)
{
return new PostDTO(
post.getId(),
post.getContents(),
post.getCreatedAt(),
null,
ImageDTO.list(post.getImages(), ImageDTO::withoutUser)
);
}
Here it just calls the method which returns a new instance of the object.
I have not seen this error before, and I'm not sure how to handle it?
Try
return Response.status(Status.OK).entity(new Gson().toJson(PostDTO.basic(post))).build();
I am trying to send a JSON string as a request to my application. This is my code:
#RequestMapping(
value = "/mylink/upload",
method = RequestMethod.POST,
consumes ="application/json",
produces = "application/json")
public
#ResponseBody
List<Upload> upload(
#RequestParam(value = "hdfsLocation") String hdfsLocation
) throws Exception {
return S3HdfsTransfer.uploadFromHDFS(hdfsLocation);
}
I am trying to send a request with Postman. The method I use is POST, the header contains: Accept "application/json",Content-Type "application/json", the request body is the following:
{
"hdfsLocation" : "hdfs://145.160.10.10:8020"
}
This is the response I get. If I put the parameter in the URL, it works.
{
"httpStatus": 500,
"appErrorId": 0,
"message": "Required String parameter 'hdfsLocation' is not present",
"trackingId": "8c6d45fd-2da5-47ea-a213-3d4ea5764681"
}
Any idea what I am doing wrong?
Thanks,
Serban
Looks like you have confused #RequestBody with #RequestParam. Do either of following :
Pass the request param as a request param(not as a body). Like, (encoded)
http://example.com?hdfsLocation=http%3A%2F%2Fexample.com%3FhdfsLocation%3Dhdfs%3A%2F%2F145.160.10.10%3A8020
Replace the #RequestParam with #RequestBody. If you are sending a body, don't send it along with request param. Those are two different things.
I guess you over looked :)
Shouldn't it be #RequestBody instead of #RequestParam?
Also, even after using #RequestBody, the whole of the JSON string:
{
"hdfsLocation" : "hdfs://145.160.10.10:8020"
}
will be the value of String hdfsLocation and not just the hdfs url. Hence, you'll have to JSON parse that JSON by yourself to get just the hdfs url.
I'm trying to make a true RestFull service and keeping to the documentation. However I'm stuck now with a problem I can't see a clear answer for. I want to use a filter to query some data from the webservice. The following path is defined on the controller of the webservice
#RequestMapping(value="/rest/postalcode/list/filter?lang={lang}&postalcode={postalcode}&country={country}&city={city}", method = RequestMethod.GET, produces="application/json")
public #ResponseBody JsonPostalCodeList findFilteredPostalCodes(#PathVariable("lang") String lang, #PathVariable("postalcode") String postalcode, #PathVariable("country") Long country, #PathVariable("city") String city, Model model) throws Exception {
}
Then I try to call it with the following method on client side
public JsonPostalCodeList findPostalCodes(
JsonPostalCodeSelectorData selectorData) {
String url = getWebserviceLocation()+"/rest/postalcode/list/filter?lang={lang}&postalcode={postalcode}&country={country}&city={city}";
MbaLog.debugLog(logger,"Calling webservice with url: " + url);
return getRestTemplate().getForObject(url, JsonPostalCodeList.class, selectorData.getContactLanguage(), selectorData.getPostalCode(), selectorData.getCountry(), selectorData.getCity());
}
now selectorData.getPostalCode() can be null for example because , the user didn't fill in a postalcode to filter on. Same can be true for country and city (lang is always filled in). But each time I run it I get an IOException not found (probably due to the null's). I tried once with everything filled in and I go perfectly in my method at service side. So how do you handle such a problem ?
I can solve it by throwing GET out of the window and just put everything in a POST body as a JSONobject mapped with Jackson and problem solved. But then I'm using a POST to fetch data while a GET should be used in pure REST to fetch data.
So RestTemplate and querying services with variable data how to go about it ?
Just took a cold shower and found it out myself :)
I don't have to use pathvariables I can just use request parameters.
#RequestMapping(value="/rest/postalcode/list/filter", method = RequestMethod.GET, produces="application/json")
public #ResponseBody JsonPostalCodeList findFilteredPostalCodes(#RequestParam("lang") String lang, #RequestParam("postalcode") String postalcode, #RequestParam("country") Long country, #RequestParam("city") String city, Model model) throws Exception {
}
and calling it with
#Override
public JsonPostalCodeList findPostalCodes(
JsonPostalCodeSelectorData selectorData) {
String url = getWebserviceLocation()+"/rest/postalcode/list/filter?lang={lang}&postalcode={postalcode}&country={country}&city={city}";
MbaLog.debugLog(logger,"Calling webservice with url: " + url);
return getRestTemplate().getForObject(url, JsonPostalCodeList.class, selectorData.getContactLanguage(), selectorData.getPostalCode(), selectorData.getCountry(), selectorData.getCity());
}
I have this piece of code:
#RequestMapping(value = "/test.json", method = RequestMethod.GET)
#ResponseStatus(HttpStatus.OK)
public #ResponseBody Object[] generateFile(#RequestParam String tipo) {
Object[] variaveis = Variavel.getListVariavelByTipo(tipo);
return variaveis;
}
As far as I know it should take a request to test.json?tipo=H and return the JSON representation of Variavel[], however when I make such request I get:
HTTP Status 406 -
type Status report
message
descriptionThe resource identified by this request is only capable of generating responses with characteristics not acceptable according to the request "accept" headers ()
By using the following function I can get the expected json:
#RequestMapping(value = "/teste.json")
public void testeJson(Model model, #RequestParam String tipo) {
model.addAttribute("data", Variavel.getListVariavelByTipo("H"));
}
What I'm doing wrong?
#RequestBody/#ResponseBody annotations don't use normal view resolvers, they use their own HttpMessageConverters. In order to use these annotations, you should configure these converters in AnnotationMethodHandlerAdapter, as described in the reference (you probably need MappingJacksonHttpMessageConverter).