Home > database >  Java springboot POST request giving 404
Java springboot POST request giving 404

Time:10-31

I am trying a POST request in POSTMAN but even though its reaching the tomcat server node, I get following error in my localhost_access.log file

"POST /app/MyService/myControllerMethod HTTP/1.1" 404 1010

My Controller class is something like this :

@Controller("myServicecontroller")
@RequestMapping({"/MyService"})
public class MyServiceController {

    @RequestMapping(value = {"myControllerMethod"}, method = {RequestMethod.POST})
    public String myControllerMethodBackgroundCallBack(HttpServletRequest httpReq,
            @RequestBody String request) {
             // rest piece of code
          }

     }

Now my postman curl I am trying with empty data (tried with some value also) but get above 404 error response

curl --location --request POST 'http://my-ip-address:8080/app/MyService/myControllerMethod' \
--header 'Accept: application/json' \
--header 'Content-Type: application/json' \
--header 'My-Header-One: lskdnansdlknalkasndl' \
--header 'My-Header-Two: sadasdsa' \
--data-raw '{}'

What am I doing wrong? (app in above url is my service which works fine in other requests)

Same thing when I try with following code it is able to hit the api 200

HttpClient httpClient = new HttpClient();
PostMethod postMethod = new PostMethod(url);
postMethod.setRequestBody(requestString);
httpClient.setConnectionTimeout(httpReadTimeOut);

httpClient.executeMethod(postMethod);

CodePudding user response:

I have successfully replicated this issue and found the root cause.

Root Cause

@ResponseBody annotation is missing in myControllerMethodBackgroundCallBack method.

Fix

    @RequestMapping(value = {"myControllerMethod"}, method = {RequestMethod.POST})
    @ResponseBody
    public String myControllerMethodBackgroundCallBack(HttpServletRequest httpReq,
            @RequestBody String request) {
             // rest piece of code
          }

     }

Why?

@ResponseBody annotation is required with @Controller annotation and if use @RestController annotation then @ResponseBody annotation is not required.

In Short-

@RestController = @Controller @ResponseBody

You can read more about @Controller and @RestController here https://medium.com/@akshaypawar911/java-spring-framework-controller-vs-restcontroller-3ef2eb360917

  • Related