I will start with: I am doing something terribly wrong. And here is what I am doing wrong.
I created a REST resource for searching something and I am expecting a JSON data in request parameters:
@GET
@Path("/device")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public Response searchContent(String searchJSONString) {
String message = new SearchServices().search(searchJSONString);
return getResponse(message); //Checks the message for any error and sends back the response.
}//end of searchContent()
I should not have written:
@Consumes
since it is a GET resource and it does not consumes anything. But my problem is how to send JSON data in a java code for this (GET resource). I tried curl command which is able to send JSON data to this resource but not a java code by any means.
I tried following curl command to send JSON data to it:
curl -X GET -H "Content-Type: application/json" -d '{"keyword":"hello"}' http://localhost:8080/search-test/rest/search
And its working fine and giving me back a proper JSON response.
But if I am using a curl command without specifying any method (which should be a default http get), I am getting a 405 (Method not allowed) response from tomcat:
curl -d '{"keyword":"hello"}' http://localhost:8080/search-test/rest/search
or through Java code:
HttpURLConnection urlConnection = (HttpURLConnection) new URL(urlString).openConnection();
urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.setRequestMethod("GET"); //This is not working.
getting the same 405 (Method not allowed) response from tomcat.
If I am sending a GET request using java code, I am not able to send the JSON data as in a post method, and I am forced to use a name=value thing and for that I need to change my REST resource to accept it as a name/value pair.
It means something like this:
http://localhost:8080/search-test/rest/search?param={"keyword":"permission"}
If I am doing something similar in POST:
@POST
@Path("/device")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public Response searchContent(String searchJSONString) {
String message = new SearchServices().search(searchJSONString);
return getResponse(message); //Checks the message for any error and sends back the response.
}//end of searchContent()
I am able to send the JSON data both from Java code and curl command as well:
curl -X POST -H "Content-Type: application/json" -d '{"keyword":"hello"}' http://localhost:8080/search-test/rest/search
or through Java code:
HttpURLConnection urlConnection = (HttpURLConnection) new URL(urlString).openConnection();
urlConnection.setRequestMethod("POST"); //Works fine.
urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.setDoOutput(true);
Where is the problem? Why am I not able to send it from code but from curl? Is there any other way to send JSON data to the GET resource other than a name=value pair?