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.
Related
So I have a simple endpoint in my Spring Boot App, which just redirects to another website:
#Controller
public class FeedbackController {
#GetMapping(path = "/test")
public Mono<ResponseEntity<Void>> method() {
String redirectUrl = "https://www.google.com";
return Mono
.just(ResponseEntity.status(HttpStatus.TEMPORARY_REDIRECT).location(URI.create(redirectUrl)).build());
}
Making a GET request to this endpoint (e.g. in browser or with postman) gives me the page content of google as a response. However for testing purposes I want to make sure that the response is a TEMPORARY_REDIRECT with www.google.com as the Location Header.
How can I make a request to this endpoint so that the response is the 307 TEMPORARY_REDIRECT instead of the 200 with page content from the target website?
First
to test if its working, you could use simple tools like curl :
We add the -L flag to tell curl that we want to know if we are getting redirected
curl -L http://www.....
Go further
Then, you could simply use tools like MockMvc to automate this test
See this SO post
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.
I just want to create a simple REST service and it uses #GET and #POST.
for the #GET function, everything is ok but for #POST, when I want to create a new user on my server the browser just keeps sating (METHOD NOT ALLOWED).
I read so many articles about how to fix this error but I haven't got anything yet.
My code for #POST :
#Path("/hello")
public class HelloResource(){
#POST
#Produces(MediaType.APPLICATION_JSON)
#Path("/post")
public Response createUser(#PathParam("name") String name,#PathParam("address") String address,#PathParam("birthYear") String birth,#PathParam("ps") String password) throws NotAllowedException,MethodNotFoundException,Exception {
DataStore.getInstance().putPerson(new Person(name, address, Integer.parseInt(birth), password));
String json = "{\n";
json += "\"status\": " + '"'+"CREATED" +'"'+ ",\n";
json+="}";
return Response.status(200).entity(json).build();
}}
I also tried adding #Consumes function with (MediaType.APPLICATION.JSON) and (MediaType.TEXT_PLAIN) but nothing changed.
Also the URL I enter for posting is :
http://localhost:8080/HelloREST/rest/hello/post?name=PouYad&address=mustbejsonlater&birthYear=2005&ps=12345
As you see I also tried so many exception handlers.
Can someone please help?
if you enter your URL in the browser URL address field, it won't work because the browser will send a "GET" request. So you must use a client that will allow you to send a "POST" like PostMan. Or write your own small httpConnection function that sends a "POST"
You also have to change the #PathParam to #FormParam for it to work (#QueryParam will also work, but because it is POST, it is best to use #FormParm).
Access URL directly through browser can only create Get Request, not POST Request
You should
Create HTML Form, set the action to your service url with POST method, and then submit it.
Use Rest Client like postman to access your service with POST method.
Write your own Http Client using java.net.http api or just simply use
one of the handy libraries/frameworks (Like Spring has RestTemplate).
I have an web application and I'm trying to creat a simple POSt method that will have a value inside the body request:
#RequestMapping(value = "/cachettl", method = RequestMethod.POST)
#CrossOrigin(origins = "http://localhost:3000")
public #ResponseBody String updateTtl(#RequestBody long ttl) {
/////Code
}
My request which I call from some rest client is:
POST
http://localhost:8080/cachettl
Body:
{
"ttl": 5
}
In the response I get 403 error "THE TYPE OF THE RESPONSE BODY IS UNKNOWN
The server did not provide the mandatory "Content-type" header."
Why is that happening? I mention that other GET requests are working perfectly.
Thanks!
Edit:
When I tried it with postman the error message I got is "Invalid CORS request".
Spring application just doesn't know how to parse your message's body.
You should provide "header" for your POST request to tell Spring how to parse it.
"Content-type: application/json" in your case.
You can read more about http methods here: https://developer.mozilla.org/en-US/docs/Learn/HTML/Forms/Sending_and_retrieving_form_data
Updated:
Just in case of debug, remove useless annotations to test only POST mechanism. Also, change types of arg and return type. And try to use case-sensitive header.
#RequestMapping(value = "/cachettl", method = RequestMethod.POST)
public void updateTtl(#RequestBody String ttl) {
System.out.println("i'm working");
}
Since the error is about the response type, you should consider adding a produces attribute, i.e :
#RequestMapping(value = "/cachettl", method = RequestMethod.POST, produces=MediaType.APPLICATION_JSON_VALUE)
Since you are also consuming JSON, adding a consumes attribute won't hurt either :
#RequestMapping(value = "/cachettl", method = RequestMethod.POST, consumes=MediaType.APPLICATION_JSON_VALUE, produces=MediaType.APPLICATION_JSON_VALUE)
The error message is slightly misleading. Your server code is not being hit due an authentication error.
Since you say spring-security is not in play then I suspect you're being bounced by a CORS violation maybe due to a request method restriction. The response body generated by this failure (if any at all) is automatic and will not be of the application/json type hence the client failure. I suspect if you hit the endpoint with something that doesn't care for CORS such as curl then it will work.
Does your browser REST client allow you to introspect the CORS preflight requests to see what it's asking for?
I have a REST service written with the Spring Framework v 3.2.0
Here is the Controller:
#Controller
#RequestMapping("/volunteer")
public class VolunteerController {
//several methods not included (all HTTP GET & working properly)
#RequestMapping(value="/{volunteerId}/assignments/{sessionId}",
method=RequestMethod.PUT, params={"worked"})
#ResponseStatus(HttpStatus.NO_CONTENT)
public void setWorkedFlag(#PathVariable int volunteerId,
#PathVariable int sessionId,
#RequestParam int worked) {
assignmentMapper.setWorked(volunteerId, sessionId, worked);
}
}
When I submit a PUT request with this URL:
http://localhost:8080/volunteer/298/assignments/1?worked=true
I get a 400 restonse with the message : The request sent by the client was syntactically incorrect.
I can also confirm that the underlying resource has not need modified.
I have compared the annotations against the request URL and can't see anything obviously wrong. Also, the other methods (omitted here) all work correctly, so the Application Context has been set up OK.
Any ideas?