How can I consume JSON object in my RESTful web server. How should be the client. I'm using Jersey server.
EX.
//BEAN
public class Student{
public String name;
}
//SERVER
#POST #Consumes("application/json")
#Path("/create")
public void create(Student s1) {
System.out.println(s1.name);
}
//CLIENT
ClientConfig config1 = new DefaultClientConfig();
Client client1 = Client.create(config1);
client1.addFilter(new LoggingFilter());
WebResource service1 = client1.resource(getBaseURI());
Student s = new WSTestClient.Student();
s.name="POP";
service1.path("create").type(MediaType.APPLICATION_JSON).post(s);
Its not working...
Most of the REST web services development framework does the marshalling of json to objects. You need to consume a json form param in POST request and assign it to a java bean object. Here is a sample method contract for the same using Jersey framework:
#POST
#Consumes(MediaType.APPLICATION_JSON)
public Response sampleRestMethod(#FormParam ("jsonStringParamName") YourCorrespondingJavaBean yourCorrespondingJavaBeanObj );
Follow this simple but really good tutorial to learn more about writing a RESTful service using jersey and json as the content type:
http://www.mkyong.com/webservices/jax-rs/json-example-with-jersey-jackson/
Problem in my client I have to add the following line to make the client post a JSON Object
config1.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE)
Have to add POJO Mapping to the ClientConfig.
Related
I'm using eBay notification API, i'm getting a SOAP web request that contains XML inside.
I would like to use jersey framework in order to deserialize the request into an object.
Is there any easy way to generate a bean class from the SOAP request that will be used in a simpler way that I'm using json? for an example :
#POST
#Path("/path")
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public Response methodName(Item bean)
{
...
}
You can generate bean class from xml response using JAXB library.
Read More about this
I've defined a RESTful WebService (by using RESTEasy on JBoss AS 7) that consumes a JSON data stream.
#PUT
#Path("/send")
#Consumes(MediaType.APPLICATION_JSON)
public Response consumeJSON(Student student) {
String output = student.toString();
// Do something...
return Response.status(200).entity(output).build();
}
How can I call my WS from another Spring-based webapp, by properly using the RestTemplate, mapping a Java Object to JSON and passing it as request body?
Note: I'm asking about Spring with the aim to investigate the facilities provided by the framework. I well know that it is possible to do that by defining manually the request body.
Cheers, V.
In the client application, you can create an interface with the same signature as the one you expose on the server side, and the same path.
Then, in the spring configuration file, you can use the RESTeasy client API to generate a proxy connecting to the exposed webservice.
In the client application, it would look like this :
SimpleClient.java
#PUT
#Path("/send")
#Consumes(MediaType.APPLICATION_JSON)
public Response consumeJSON(Student student);
Config.java
#Bean
public SimpleClient getSimpleClient(){
Client client = ClientFactory.newClient();
WebTarget target = client.target("http://example.com/base/uri");
ResteasyWebTarget rtarget = (ResteasyWebTarget)target;
SimpleClient simple = rtarget.proxy(SimpleClient.class);
return simple;
}
Then, in the place where you want to invoke this web service, you inject it with Spring and you can call the method. RESTeasy will search for the webservice matching with with your client (according to the path and the request type) and will create a connection.
Launcher.java
#Resource
private SimpleClient simpleClient;
public void sendMessage(Student student) {
simpleClient.consumeJSON(student);
}
Docs on the RESTesay client API : http://docs.jboss.org/resteasy/docs/3.0.7.Final/userguide/html/RESTEasy_Client_Framework.html
Hope this was helpfull.
here is one controller i got on my web application:
#RequestMapping(value = "/createAccount", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
#ResponseStatus(value = HttpStatus.OK)
#ResponseBody
public ResponseDTO createAccount(#RequestBody PlayerAccountDTO playerAccountDTO,
HttpServletRequest request) {
this.playerService.createAccount(playerAccountDTO);
return new ResponseDTO();
}
This controller is being called via ajax using post and passing a json and jackson mapper takes care for it to arrive as a POJO (Nice!)
What i would like to do now is:
In a different web application i would like to call with http post request passing PlayerAccountDTO to this exact controller and ofcourse recieve the ResponseDTO.
I would like that to be as simple as possible.
Is it possible to achieve that? here is my wishfull solution (a service on a different web app):
public ResponseDTO createAccountOnADifferentWebApp() {
PlayerAccountDTO dto = new PlayerAccountDTO(...);
ResponseDTO result = httpRequestPost(url, dto, ResponseDTO.class);
return result;
}
Your web server doesn't receive a PlayerAccountDTO object. It receives an HTTP request with a body that (likely) contains a JSON object. The Spring web application tries to deserialize that JSON into a PlayerAccountDTO object which it passes to your handler method.
So what you want to do is use an HTTP client which serializes your PlayerAcocuntDTO on the client side into some JSON which you send in an HTTP request.
Check out RestTemplate which is a Spring HTTP client and uses the same HttpMessageConverter objects that Spring uses to serialize and deserialize objects in #ResponseBody annotated methods and #RequestBody annotated parameters.
You can do it using commons-http-client library
I took a look at the Dropwizard framework and I want to use it to package my existing REST service.
In the tutorial I noticed that the response content type is not set using a ResponseBuilder, can I set the reponse type like I would do for a regular REST service if it were not in a Dropwizard framework ?
The reason I want to set a dynamic response content type is because the webservice does not know the kind of data it is serving.
Thanks
You should be able to just return a Response object and adjust the type. For instance:
#Path("/hello")
#Produces(MediaType.TEXT_PLAIN)
public class Example{
#GET
public Response sayHello() {
return Response.ok("Hello world").type(MediaType.TEXT_HTML).build();
}
}
I am trying to write a java client for restful resource. The response for my request is a list of objects. I have the following code for the request. BUt i get some unmarshall exception. Could anyone let me know how to solve this ?
GenericType<List<Response>> genType = new GenericType<List<Response>>() {};
GenericType<List<Response>> response = (GenericType<List<Response>>)resource.path(paramPath).accept(MediaType.APPLICATION_JSON).get(genType);
my resource has the following code
#GET
#Path("/app/{Id}")
#Produces(MediaType.APPLICATION_JSON)
public List<Response> getAllKeyValuesByAppId(#PathParam("Id") Long Id){
...
...
}
Can you test you REST method without unmarshaling?
Are you sure that the message body contains exactly what you expect?