getting http 400 bad request spring mvc - java

I am working on Spring mvc project.
I have to implement rest apis, one api which i am implementing now return http 400 bad request. in it get method request. another api working properly for same json but this api returns HTTP 400
controller function
#RequestMapping(value = "/getSlotsByDateRange/hosid/{hos_id}/from/{start_date}/to/{end_date}" , method = RequestMethod.GET, produces = "application/json")
public ResponseEntity<SlotByDateRange> getSlotsByDateRange(#PathVariable String hos_id,#PathVariable String start_date,#PathVariable String end_date) {
return new ResponseEntity<SlotByDateRange>(hospitalService.getSlotsByDateRange(hos_id,start_date,end_date),HttpStatus.ACCEPTED);
}
Request url:
getSlotsByDateRange/hosid/0009/from/2021-04-15/to/2021-04-22

I have just implemented it and it is working for me.
#GetMapping(value = "/getSlotsByDateRange/hosid/{hos_id}/from/{start_date}/to/{end_date}" , produces = "application/json")
For get requests you can use #GetMapping instead of #RequestMapping. As #GetMapping itself contains
#RequestMapping(
method = {RequestMethod.GET}
)
Hope this helps someone else as well.

Related

RestTemplate for #RequestBody and #RequestParam

I'm trying to use RestTemplate to call POST api like that :
RequestorParam test = new RequestorParam();
test.setScopeMcg("MCG");
test.setSituatedDealIds(situatedDealIds);
String url = "http://localhost:" + serverPort + "/retrieveAttributes";
ResponseEntity<SituatedDeals> response = restTemplate.postForEntity(url, test, SituatedDeals.class);
and the code of the controller is like ;
#PostMapping(value = "/retrieveAttributes", produces = "application/json")
#ResponseBody
#Duration
public SituatedDeals retrieveAttributes(
#RequestParam String scopeMcg,
#RequestBody SituatedDealIds situatedDealIds
) {
log.info("success")
}
i'm getting bad request, can someone help ?
According to your controller code, you are actually not returning any Response Entity of type SituatedDeals, just logging it as success. this might be the reason for the null object in response.
The scopeMcg is a RequestParameter so you should be passing it in a request param format i.e http://localhost:8080/retrieveAttributes?scopeMcg=MCG
Reference:Spring Request Param
Your test Object is the actual payload for your post request which should be of type SituatedDealIds object.
Reference: Rest-Template post for Entity

Spring boot consuming rest api in Gradle

I'm completely new to Java and trying to consume a rest API with Spring Boot in Gradle, so far I've managed to make a very basic get request to display a message like below
#RestController
public class HelloController {
#RequestMapping(value = "/hello", method = RequestMethod.GET)
public String printWelcome(ModelMap model) {
model.addAttribute("message", "Hello");
return "hello";
}
}
Now, how to extend this get request to make HTTP requests consume an endpoint based on RestTemplate, assuming this is my endpoint that i want to consume like below:
RestTemplate restTemplate = new RestTemplate(); ResponseEntity response = restTemplate.getForEntity("http://aws.services.domain.com/country/id", String.class);
Finally, I want to achieve authorized HTTP GET requests by adding a token Bearer in the Authorization header.
Thank you for answers and suggestions in advance
If you want to add a header, you have to use exchange or execute method.
So, in your case:
HttpHeaders headers = new HttpHeaders();
headers.set("Authorization", "Your Bearer Token");
HttpEntity entity = new HttpEntity(headers);
ResponseEntity<String> response = restTemplate.exchange(
url, HttpMethod.GET, entity, String.class, param);

Receiving a POST Request on Spring From Another Site

I'm a little new in Java Spring. What I want to do is as follows:
Some 3rd party is asking a "return URL" from me and I set it as follows:
https://localhost:9002/my-account/order-history
Then they send me a POST request and I'm supposed to handle it within my controller. The request has both url parameters and a form data. The request is
Request URL:https://localhost:9002/my-account/order-history?responseCode=0000&token=E0ECFC1214B19E5D11B9B587920FC5F164C5CB17E7DC67F083E0EC6676F79467DFBDF4B6CCF3C39BF47F0232D1AA42F1FA112F29B0157DDF98EE3997F781CCB1FEB070A44E530691BA36674BEA4CF56A4A43F2B9746D9C3591CF288D745A6694
Request Method:POST
Status Code:403 Bad or missing CSRF token
Remote Address:127.0.0.1:9002
Referrer Policy:no-referrer-when-downgrade
A part of the form data is:
I added the whole form data and other request info as attachment.
The controller I'm desperately trying to use is as follows:
#Controller
#RequestMapping(value = "/my-account")
public class MaviAccountPageController extends MaviAbstractController
{
#RequestMapping(value = "/order-history", method = RequestMethod.POST)
public ModelAndView process(#RequestBody final String req)
{
//consumes = "text/plain"
System.out.println(req);
System.out.println(req);
return new ModelAndView("deneme");
}
....
}
And I keep getting 403 - Bad or missing CSRF token error.
How should I implement my controller? I have checked below links and they did not work out unfortunately:
How to retrieve FORM/POST Parameters in Spring Controller?
How to explicitly obtain post data in Spring MVC?
I tried, but failed to regenerate issue on postman.
Can anyone, please, advise me about how to move on?
you can annotate your method with #CrossOrigin
#CrossOrigin
#RequestMapping(value = "/order-history", method = RequestMethod.POST)
public ModelAndView process(#RequestBody final String req)
{
//consumes = "text/plain"
System.out.println(req);
System.out.println(req);
return new ModelAndView("deneme");
}
https://spring.io/guides/gs/rest-service-cors/

Spring mvc - send xml text string to controller

I'm working on a java spring mvc application. I need to send an xml string to my controller, and get this xml as a simple text string inside controller. But can not find any solution yet. I tried this way:
#RequestMapping(value = "/test", method = RequestMethod.POST)
public String test(String post, HttpServletRequest request, HttpServletResponse response){
System.out.println("post: " + post);
}
and I have contentType: 'text/xml' in my ajax config. But the variable post always printed as null.
Also I tried consumes = MediaType.APPLICATION_XML_VALUE and consumes = MediaType.TEXT_XML_VALUE in my method, but returns me HTTP Status 415 – Unsupported Media Type. What is the problem? How can I send simple xml text to my controller?
You can read your string using RequestParam:
#RequestMapping(value = "/test", method = RequestMethod.POST)
public String test(
#RequestParam(value="post") String post, Model model){
...
}

How to get JSON as Response in Spring MVC?

I am trying to return response as JSON. After searching I found solution to add headers = "Accept=application/json" in RequestMapping. But still it is not working .
It is throwing error HTTP Status 406 "The resource identified by this request is only capable of generating responses with characteristics not acceptable according to the request "accept" headers."
Here is my controller code :
#RestController
public class EmployeeController {
private EmployeeService employeeService;
#Autowired(required = true)
#Qualifier(value = "employeeService")
public void setEmployeeService(EmployeeService employeeService){
this.employeeService = employeeService;
}
#RequestMapping(value = "/test",method = RequestMethod.GET)
public String test(){
return "{\"name\":\"xyz\"}";
}
#RequestMapping(value = "/employees",method = RequestMethod.GET,headers = "Accept=application/json")
public List<Employee> listEmployees(){
List<Employee> employees = this.employeeService.getEmployees();
return employees;
}
}
Where am I doing wrong?
The simple way to generate JSON, XML response is #ResponseBody annotation.
#RequestMapping(value =" /jsonPostSingle", method = RequestMethod.GET)
#ResponseBody
public PostModel generateJSONPostsingle(#ModelAttribute("postModel") PostModel postModel) {
if(postModel.getPostId() == 1) {
postModel.setTitle("post title for id 1");
} else {
postModel.setTitle("default post title");
}
return postModel;
}
This way you will be able to map your request to model class using #ModelAttribute.
Follow the complete tutorial Spring MVC : JSON response using #ResponseBody
I understand that you're trying to send a response from GET request of /employees.
if you are using Spring 3.1, try to use
#RequestMapping(value = "/employees",method = RequestMethod.GET, produces = "application/json")
instead of adding headers = "Accept=application/json"
More info:
if you want to specify type of data that will send with a request, you can use consumes attribute
example:
#RequestMapping(value="/foo", method = RequestMethod.POST, consumes = "application/json", produces = "application/json")
this will consumes and response with JSON type only
check this link about spring update http://spring.io/blog/2011/06/13/spring-3-1-m2-spring-mvc-enhancements/
Hope it helps

Categories