Receiving JSON Response - java

I am trying to receive a JSON response with Jersey but it is always sending null. Here is my service code:
#POST
#Consumes(MediaType.APPLICATION_JSON)
#Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML,
MediaType.TEXT_XML })
#Path("/songs/")
public Room AddSong(#PathParam("json") String Info) {
Song newSong = new newSong();
newSong.addSong(Info);
return newSong;
}
In this case, "Info" is always null. I receive a 200 response from the server so I know the JSON is being sent. The only other thing im not sure is, should I sent JSON in UTF-8?

First of all, you need to use #PathParam correctly. You need to specify {json} in your url. Look at the example
UPD: It's just occurred to me, you in your case you don't need to use #PathParam at all. Just put it away and it should work.

Path parameters take the incoming URL and match parts of the path as a parameter. By including {name} in a #Path annotation, the resource
can later access the matching part of the URI to a path parameter with
the corresponding "name". Path parameters make parts of the request
URL as parameters which can be useful in embedding request parameter
information to a simple URL.
#Path("/books/{bookid}")
public class BookResource {
#GET
public Response invokeWithBookId(#PathParam("bookid") String bookId) {
/* get the info for bookId */
return Response.ok(/* some entity here */).build();
}
#GET
#Path("{language}")
public Response invokeWithBookIdAndLanguage(#PathParam("bookid") String bookId, #PathParam("language") String language) {
/* get the info for bookId */
return Response.ok(/* some entity here */).build();
}
}
In your rest code argument Info takes value from #Path("/songs/{json}") but you have specify #Path("/songs/") so json will always be null
#POST
#Consumes(MediaType.APPLICATION_JSON)
#Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML,
MediaType.TEXT_XML })
#Path("/songs/")
public Room AddSong(#PathParam("json") String Info) {
Song newSong = new newSong();
newSong.addSong(Info);
return newSong;
}
You do like this and then everything will be fine :
#POST
#Consumes(MediaType.APPLICATION_JSON)
#Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML,
MediaType.TEXT_XML })
#Path("/songs/{json}")
public Room AddSong(#PathParam("json") String Info) {
Song newSong = new newSong();
newSong.addSong(Info);
return newSong;
}
For more info refer JAX-RS Parameters

You do not need the #PathParam as the JSON contents should be in the POST body. You have declared the return type to be Room, but are you not trying to return type Song? Assuming this is a simple JSON wrapped string, the contents are in the POST body, and you want Song returned in the 200 OK then you can try this:
#POST
Consumes(MediaType.APPLICATION_JSON)
#Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML, MediaType.TEXT_XML })
#Path("/songs/")
public Song AddSong(String Info) {
Song newSong = new newSong();
newSong.addSong(Info);
return newSong;
}
Optionally, if you want to use a JSON representation of Song in the API, you can replace String Info with Song newSong and then specific Song in the POST body.

Related

Dropwizard Rest API endpoint manipulation

I have a dropwizard application to POST/GET query information. I have a #POST method that populates an arrayList with my query and its' 11 parameters. For brevity, I cut the example down to only show 3 parameters.
#Path("/query")
public class QueryResource
#GET
#Produces(MediaType.APPLICATION_JSON)
#Timed
public List<Query> getQueries() {
List<Query> queries = new ArrayList<Query>();
logger.info("Calling get queries with {} method.");
queries.add(new Query("b622d2c6-03b2-4488-9d5d-46814606e550", "eventTypeThing", "action"));
return queries;
I can send a get request through ARC and it will return successful with a json representation of the query.
I run into issues when I try to make a #GET request on the specific queryId and return a specific parameter of it. As such,
#GET
#Path("/{queryId}/action")
public Response getAction(#PathParam("queryId") String queryId, #PathParam("action") String action){
logger.info("Get action by queryId {}");
String output = "Get action: " + action;
return Response.status(200).entity(output).build();
On the rest client I make a get request to https://localhost/query/b622d2c6-03b2-4488-9d5d-46814606e550/action
I'm expecting that to return the action type of that specific queryId, but instead is returning null.
You did not declare "action" as a proper param in the #Path annotation of the method. You need to change that to:
#Path("/{queryId}/{action}")

JAX-RS inject the value of URI parameter

I am trying to get the user by id with the following method:
#Path("/v1/user/")
public class UserRestService extends BaseRestWebService {
#GET
#Path("/customers/{id}")
#Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public Catalog getCustomerById(#Context HttpServletRequest httpServletRequest, #PathParam("id") String userId){
IlsCustomer customer = getUserService().getUserById(IlsCustomer.class, Long.parseLong(userId));
Catalog catalog = new Catalog();
catalog.add(customer);
return catalog;
}
}
I am using Postman and in postman when I type: https://localhost:8181/iPCP/restServices/v1/user/customers/6560
I am getting error :
The page cannot be found (404)
You tried to access a page that does not exist. Please check the entered URL.
But if I type URL: https://localhost:8181/iPCP/restServices/v1/user/customers
the response is: {}

Java: PUT request without id getting submitted as POST

I have create and update api calls for same entities. If user send a PUT request with no object id, controller accepts it as a POST request and creates a new object. How can I prevent that?
#POST
#Consumes({MediaType.APPLICATION_XML})
#Produces({MediaType.APPLICATION_XML})
public Response create(Entity entity){}
#PUT
#Path("/{id}")
#Consumes({ MediaType.APPLICATION_XML })
#Produces({ MediaType.APPLICATION_XML })
public Response update(#PathParam("id") int id,Entity entity){}
Is there a way to make request parameter required for update? That may resolve the issue as well.
Add a RegEx pattern from your #Path.
Syntax:
#Path("/{" variable-name [ ":" regular-expression ] "}")
Example:
#Path("/{id: <replace_with_reg_exp>}")

How to get a string sent in body of a request inside a Spring restful webservice?

I have a spring web service method where i want to get a string as a parameter. The string is sent in body of the request. My web service class is:
#Controller
#RequestMapping(value = "/users/{uid}/openchart")
public class OpenChartWebService {
#RequestMapping(method = RequestMethod.POST)
#ResponseBody
public String saveABC(#PathVariable("uid") Long uid,
#RequestBody String myString) {
System.out.println("sent string is: "+myString);
return "something";
}
}
My request in body is :
{
"name":"Ramesh"
}
But this is not working. This shows "Bad Request" HTTP error(400). How to send a string in a body and how to get a string sent in a body inside webservice method?
As #Leon suggests, you should add the media type to your request mapping, but also make sure you have Jackson on your classpath. You'll also want to change your #RequestBody argument type to something that has a "name" property, rather than just a String so that you don't have to convert it after.
public class Person {
private name;
public getName() {
return name;
}
}
If your data object looked like the above, then you could set your #RequestBody argument to Person type.
If all you want is a String, then perhaps just pass the value of "name" in your request body rather than an object with a name property.

Jersey Deserialize Post Param with an additional Id

I'm just wondering how to modify the following
#POST
#Consumes(MediaType.APPLICATION_JSON)
public Response createObject(Object object) {
...
}
to also allow a path parameter? I was thinking something like
#POST
#Path("{server}")
#Consumes(MediaType.APPLICATION_JSON)
public Response createObjectOnServer(#PathParam("server") String url, Object object) {
...
}
but that either is just wrong or I don't know how the json should be structured.
The second block of code should work, in my project:
#POST
#Path("/{mode}")
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.TEXT_PLAIN)
public String renderWidget(#PathParam("mode") String mode,RenderingRequest renderingRequest){
...
}
where 'mode' is a path param and 'RenderingRequest' is a pojo that maps the request body(a json).

Categories

Resources