Praveen Somayaji
Praveen Somayaji

Reputation: 57

How to perform POST requests to a REST webservice?

I have a RESTful webservice, in which I have written a method which receives POST requests.

I am trying to access that method via the URL http://localhost:8091/prjctname/post.

But its throwing the following error:

HTTP Status 405 - Request method 'GET' not supported
type: Status report
message: Request method 'GET' not supported
description: The specified HTTP method is not allowed for the requested resource

Below is the code snippet.

@RequestMapping(value = "/post", method = RequestMethod.POST)
@Produces("application/json")
@ResponseBody 
public String createUser(@RequestBody PCDBean bean, HttpServletRequest request) {

    String username = null;
    String password = null;
    System.out.println("inside post method");

    String result = service.getCustomer(username, password);
    if(result != null) {
        return username + password;
    } else {
        return "failure";
    }
}

Upvotes: 2

Views: 24931

Answers (3)

qian
qian

Reputation: 1

You need to get the browser to accept a post request, like this:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Login Page</title>
</head>
<body>

<form action="login" method="post">
    name: <input type="text" name="name"> <br>
    password: <input type="password" name="password"> <br>
    <input type="submit" value="submit">
</form>

</body>
</html>

Upvotes: 0

Enrique Assis
Enrique Assis

Reputation: 11

The real issue in my case was that my text wasn't exactly the one expected in the server. The object had a spelling error. Should be exactly "{\n"+"\"jobName\":\"MOVE_TO_PICK_POSITION\"\n"+"}"; and I was using something else.

The 405 error message made me waste a lot of time since it made me think that there was some problem with my POST request.

Hope this helps.

Upvotes: 1

cassiomolin
cassiomolin

Reputation: 130917

Explaining the 405 error

You are performing a GET request to an endpoint that only supports POST requests. In this situation, the expected result is a 405 error:

6.5.5. 405 Method Not Allowed

The 405 (Method Not Allowed) status code indicates that the method received in the request-line is known by the origin server but not supported by the target resource. [...]

Picking the right tool

I guess you are trying to access the endpoint using the browser address bar. However, when typing the resource URL in the browser address bar, you are performing a GET request. That's the default behavior of the browser. Deal with it.

Hence, the browser address bar won't give you much flexibility to test a REST API, once you only can perform GET requests from it.

To test a REST API, you should use the right tools. They will give you the ability to perform requests using all the HTTP methods (including POST), set request headers and other features that are not available in the browser address bar.

Just listing a few:

Upvotes: 12

Related Questions