I’m writing a basic web service using jax-rs. I’m testing the application using the following JQuery. I can access the parameters fine using the GET parameters but when I use POST, it fails. I use the following JQuery to test both only switching “POST” to “GET”.
$.ajax({
type: "POST",
url: "http://localhost:8080/MyWebService/",
data: 'text=this is text',
dataType: 'jsonp',
success: function(data){
console.log(data);
},
error: function(){alert('failure');}
});
The java end looks like the following. Please keep in mind I am not having any issues with the get portion.
@GET
public Response getWork(@QueryParam("callback") String callbackName, @QueryParam("text") String searchText,
@Context HttpServletResponse response, @Context HttpServletRequest request) throws JsonGenerationException,
JsonMappingException, IOException {
System.out.println(searchText);
return work(callbackName, searchText, response, request);
}
@POST
public Response postWork(@FormParam("callback") String callbackName, @FormParam("text") String searchText,
@Context HttpServletResponse response, @Context HttpServletRequest request) throws JsonGenerationException,
JsonMappingException, IOException {
System.out.println(searchText);
return work(callbackName, searchText, response, request);
}
When using GET, it prints the text but when using POST, it prints null. What is needed to be able to access the parameters using the POST method?
If you send form data, you should assign what type of content server will consume. So you should annotate POST method with
@Consumes(MediaType.APPLICATION_FORM_URLENCODED). In other words, POST method should be something like this: