I am working on (Maven Project) REST with Java (JAX-RS) using Jersey. I am trying to delete a Module according to the passed id
#DELETE
#Path("delete/{id}")
#Consumes({MediaType.APPLICATION_JSON})
#Produces({MediaType.APPLICATION_JSON})
public Module deleteModuleById(#PathParam("id") Long id) {
return repository.delete(id);
}
I am getting 405 - Method not allowed from tomcat server, not sure what am I doing wrong.
This is the Delete Method:
public Module delete(long id) {
EntityManager em = EM_FACTORY.createEntityManager();
em.getTransaction().begin();
Module m = em.find(Module.class, id);
if (m != null) {
em.remove(m);
} else {
throw new IllegalArgumentException("Provided id " + id + " does not exist!");
}
em.getTransaction().commit();
em.close();
return m;
}
Postman request for all Module:
Postman request for delete module with id=1:
Project Structure:
Your code seems to be ok. Check your Sending method. Please take into account that IllegalArgumentException will probably lead to 500 - Server error
Check via Curl
curl -X DELETE <YOUR HOST>/delete/123
Or check via any external resources like https://reqbin.com/, postman, etc.
As your code seems fine and you haven't added your postman request, I assume you may have set the wrong method type in your request. you set your request like this image below:
Please, replace base_url and your_id with your actual values
N.B: check the DELETE method I have set on left of the URL
#Consumes({MediaType.APPLICATION_JSON})
Postman automatically attaches the Content-Type header according to the settings of your request's body.
Your requests are set to HTML, not JSON.
It should give a different error, but this should cause an issue here.
405 Method not allowed occurs when you try to POST while the method is GET, for example.
In the postman requests I don't see you putting the param id. So, the call you are making will look like /api/modules/delete while it should have been /api/modules/delete/1. And if there is a method like api/modules/{x}, it will call this method finally creating the 405.
Related
I want to make a GET request to my server that receives two parameters, uniqueConfig and commitHash. The code for this operation in my Controller class is as follows:
#GetMapping("/statsUnique")
public ResponseEntity<Object> hasEntry(#RequestParam("uniqueConfig") String uniqueConfig,
#RequestParam("commitHash") String commitHash) {
Optional<Stats> statsOptional =
codecService.findByUniqueConfigAndCommitHash(uniqueConfig, commitHash);
if (statsOptional.isPresent()) {
return ResponseEntity.status(HttpStatus.OK).body(true);
}
return ResponseEntity.status(HttpStatus.OK).body(false);
}
The issue is, when I try to make the GET request using Postman, the server returns a 400 - Bad Request with the following error message:
MissingServletRequestParameterException: Required request parameter 'uniqueConfig' for method parameter type String is not present]
my JSON on Postman looks like this:
{
"commitHash": "ec44ee022959410f9596175b9424d9fe1ece9bc8",
"uniqueConfig": "bowing_22qp_30fr_29.97fps_fast-preset"
}
Please note that those aren't the only attributes and I've tried making the same request with all of them on the JSON. Nonetheless, I receive the same error.
What am I doing wrong here?
A GET request doesn't (or at least shouldn't) have a body. Parameters defined by the #RequestParam annotations should be sent in the query string, not a JSON body, i.e., the request should be something like
http://myhost/statsUnique?commitHash=commitHash&uniqueConfig=bowing_22qp_30fr_29.97fps_fast-preset
I already search tutorial in spring for method POST, insert the data with response entity (without query) and I getting error in ajax. I want to confirm, What is format url from ajax to java? below my assumption:
localhost:8080/name-project/insert?id=1&name=bobby
is the above url is correct? because I failed with this url. the parameter is id and name.
mycontroller:
#PostMapping(value={"/insertuser"}, consumes={"application/json"})
#ResponseStatus(HttpStatus.OK)
public ResponseEntity<?> insertUser(#RequestBody UserEntity user) throws Exception {
Map result = new HashMap();
userService.insertTabelUser(user);
return new ResponseEntity<>(result, HttpStatus.CREATED);
}
my daoimpl:
#Transactional
public String insertUser(UserEntity user) {
return (String) this.sessionFactory.getCurrentSession().save(user);
}
the code running in swagger (plugin maven) but not run in postman with above url.
Thanks.
Bobby
I'm not sure, but it seems that you try to pass data via get params (id=1&name=bobby), but using POST http method implies to pass data inside body of http request (in get params, as you did, data is passed in GET method) . So you have to serialize your user data on client side and add this serialized data to request body and sent it to localhost:8080/name-project/insert.
As above answer suggest. You are trying to pass data as query parameters.but you are not reading those values in your rest API.either you need to read those query parameters in your API and then form an object or try to pass a json serialized object to your Post api as recommendation. Hope it helps.
I'm using Jersey to create REST API. I have one POST method and as a response from that method, the user should be redirected to a custom URL like http://example.com that doesn't have to be related to API.
I was looking at other similar questions on this topic here but didn't find anything that I could use.
I'd suggest altering the signature of the JAX-RS-annotated method to return a javax.ws.rs.core.Response object. Depending on whether you intend the redirection to be permanent or temporary (i.e. whether the client should update its internal references to reflect the new address or not), the method should build and return a Response corresponding to an HTTP-301 (permanent redirect) or HTTP-302 (temporary redirect) status code.
Here's a description in the Jersey documentation regarding how to return custom HTTP responses: https://jersey.java.net/documentation/latest/representations.html#d0e5151. I haven't tested the following snippet, but I'd imagine that the code would look something like this, for HTTP-301:
#POST
public Response yourAPIMethod() {
URI targetURIForRedirection = ...;
return Response.seeOther(targetURIForRedirection).build();
}
...or this, for HTTP-302:
#POST
public Response yourAPIMethod() {
URI targetURIForRedirection = ...;
return Response.temporaryRedirect(targetURIForRedirection).build();
}
This worked for Me
#GET
#Path("/external-redirect2")
#Consumes(MediaType.APPLICATION_JSON)
public Response method2() throws URISyntaxException {
URI externalUri = new URI("https://in.yahoo.com/?p=us");
return Response.seeOther(externalUri).build();
}
I have a web service with 3 endpoints. as follows -
GET /Game/getGameAll/ (com.service.rest.Game)
GET /Game/getGameById/{gameId} (com.service.rest.Game)
POST /Game/updateGame/{gameId}/{isAvailable} (com.service.rest.Game)
For testing I use -
localhost:8080/Game/getGameAll/
localhost:8080/Game/getGameById/1000
and it works perfectly fine.
but when executing update functionality -
localhost:8080/Game/updateGame/1000/true
it gives me an error 404: method not found.
But if i change the annotation from post to get. It executes.
//#POST : If this is changed to Get, it works! But not with #POST.
#GET
#Path(value = "/updateGame/{gameId}/{isAvailable}")
#Produces(MediaType.APPLICATION_JSON)
public Game updateGame(
#PathParam(value = "gameId") Integer gameId,
#PathParam(value = "isAvailable") int isAvailable) { ..
.
}
How can i execute the Post method of a webservice?
Are you trying this from your web browser? You won't be able to call POST methods that way.
You can either use curl from your command line or an interactive client such as Postman.
Well I have a strange problem with executing a "DELETE" HTTP request in Spring.
I have a controller method which I have mapped a DELETE request to:
#RequestMapping(value = "/{authorizationUrl}",method=DELETE)
public void deleteAuthorizationServer(
#RequestHeader(value="Authorization") String authorization,
#PathVariable("authorizationUrl") String authorizationUrl)
throws IOException {
System.out.println("TEST");
}
The controller is mapped using #RequestMapping("/authorization_servers");
When I send a request through my DEV Http Client, I am getting the response : 405 Http method DELETE is not supported by this URL.
The request looks like this:
DELETE localhost:8080/authorization_servers/asxas
Headers:
Authorization: "test:<stuff>"
If someone can look into this and help me, I would be grateful
This will work:
#RequestMapping(value = "/{authorizationUrl}", method = DELETE)
#ResponseBody
public void deleteAuthorizationServer(
#RequestHeader(value="Authorization") String authorization,
#PathVariable("authorizationUrl") String authorizationUrl
){
System.out.printf("Testing: You tried to delete %s using %s\n", authorizationUrl, authorization);
}
You were missing #ResponseBody. Your method was actually getting called; it was what happened after that that was producing the error code.
Your annotation should look like this:
#RequestMapping(value = "/{authorizationUrl}",method=RequestMethod.DELETE)
I don't know where you got that DELETE variable from. :-)
If the #RequestMapping pattern doesn't match or is invalid, it results in a 404 not found. However, if it happens to match another mapping with a different method (ex. GET), it results in this 405 Http method DELETE is not supported.
My issue was just like this one, except my requestMapping was the cause. It was this:
#RequestMapping(value = { "/thing/{id:\\d+" }, method = { RequestMethod.DELETE })
Do you see it? The inner closing brace is missing, it should be: { "/thing/{id:\\d+}" } The \\d+ is a regular expression to match 1 or more numeric digits. The braces delimit the parameter in the path for use with #PathVariable.
Since it's invalid it can't match my DELETE request:
http://example.com/thing/33
which would have resulted in a 404 not found error, however, I had another mapping for GET:
#RequestMapping(value = { "/thing/{id:\\d+}" }, method = { RequestMethod.GET })
Since the brace pattern is correct, but it's not a method DELETE, then it gave a error 405 method not supported.
I needed to return ResponseEntity<Void> (with custom response status) instead of setting custom response status on HttpServletResponse (from endpoint method param).
ex: http://shengwangi.blogspot.com/2016/02/response-for-get-post-put-delete-in-rest.html
also make sure you're calling it with "Content-Type" header="text/html". If not, then change it or specify it in the requestMapping. If it doesn't match, you get the same 405.