Consuming POST Request in RESTEasy

Earlier, I used POSTMAN tool to submit GET/PUT/POST/DELETE but right now I am trying to implement a POST operation without using any REST API client. For this purpose I referred to this website. I created a Maven project and these are my sample codes:

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee     http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">
<display-name>RESTEasyJSONExample</display-name>

<servlet-mapping>
    <servlet-name>resteasy-servlet</servlet-name>
    <url-pattern>/rest/*</url-pattern>
</servlet-mapping>

<!-- Auto scan REST service -->
<context-param>
    <param-name>resteasy.scan</param-name>
    <param-value>true</param-value>
</context-param>

<!-- this should be the same URL pattern as the servlet-mapping property -->
<context-param>
    <param-name>resteasy.servlet.mapping.prefix</param-name>
    <param-value>/rest</param-value>
</context-param>

<listener>
    <listener-class>
        org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap
        </listener-class>
</listener>

<servlet>
    <servlet-name>resteasy-servlet</servlet-name>
    <servlet-class>
        org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher
    </servlet-class>
</servlet>

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.java.resteasy</groupId>
  <artifactId>RESTEasyJSONExample</artifactId>
  <version>0.0.1-SNAPSHOT</version>

<repositories>
    <repository>
        <id>JBoss repository</id>
        <url>https://repository.jboss.org/nexus/content/groups/public-jboss/</url>
    </repository>
</repositories>

<dependencies>

    <dependency>
        <groupId>org.jboss.resteasy</groupId>
        <artifactId>resteasy-jaxrs</artifactId>
        <version>3.0.4.Final</version>
    </dependency>

    <dependency>
        <groupId>org.jboss.resteasy</groupId>
        <artifactId>resteasy-jackson-provider</artifactId>
        <version>3.0.4.Final</version>
    </dependency>

    <dependency>
        <groupId>org.jboss.resteasy</groupId>
        <artifactId>resteasy-client</artifactId>
        <version>3.0.4.Final</version>
    </dependency>

</dependencies>

Java Class to be represented to JSON

(Student.java)

package org.jboss.resteasy;

public class Student {

private int id;
private String firstName;
private String lastName;
private int age;

// No-argument constructor
public Student() {

}

public Student(String fname, String lname, int age, int id) {
    this.firstName = fname;
    this.lastName = lname;
    this.age = age;
    this.id = id;
}

//getters and settters

@Override
public String toString() {
    return new StringBuffer(" First Name : ").append(this.firstName)
            .append(" Last Name : ").append(this.lastName)
            .append(" Age : ").append(this.age).append(" ID : ")
            .append(this.id).toString();
}

}

REST Service to produce and consume JSON output

RESTEasyJSONServices.java

package org.jboss.resteasy;

//import everything here

@Path("/jsonresponse")
public class RestEasyJSONServices {

@GET
@Path("/print/{name}")
@Produces("application/json")
public Student produceJSON( @PathParam("name") String name ) {

    Student st = new Student(name, "Marco",19,12);

    return st;

}

@POST
@Path("/send")
@Consumes("application/json")
public Response consumeJSON(Student student) {

    String output = student.toString();

    return Response.status(200).entity(output).build();

}
}

RESTEasyClient.java

package org.jboss.resteasy.restclient;

//import everything here
public class RESTEasyClient {
public static void main(String[] args) {

Student st = new Student("Catain", "Hook", 10, 12);
try {
ResteasyClient client = new ResteasyClientBuilder().build();

ResteasyWebTarget target = client.target("http://localhost:8080/RESTEasyJSONExample/rest/jsonresponse/send");

Response response = target.request().post(Entity.entity(st, "application/json"));

        if (response.getStatus() != 200) {
            throw new RuntimeException("Failed : HTTP error code : "
                    + response.getStatus());
        }

        System.out.println("Server response : \n");
        System.out.println(response.readEntity(String.class));

        response.close();

    } catch (Exception e) {

        e.printStackTrace();

    }

}
}

Now I am getting the output whenever I use the GET url:

http://localhost:8080/RESTEasyJSONExample/rest/jsonresponse/print/James

which is basically used to produce the JSON but when I use the POST url which is http://localhost:8080/RESTEasyJSONExample/rest/jsonresponse/send I do not get any response. Am I using the correct URL? Where am I doing wrong? My overall purpose is to implement POST method using JSON or XML without using any REST Client tool like POSTMAN.

Answers


HI i have Used Jersey Client to post the request. i am able to post XML data. that should work for Json also. Please refer how to build REST Client: http://entityclass.in/rest/jerseyClientGetXml.htm

REST Service

@Path("/StudentService")
public class StudentService {

    @POST
    @Path("/update")
    @Consumes(MediaType.APPLICATION_XML)
    public Response consumeXML( Student student ) {

        String output = student.toString();

        return Response.status(200).entity(output).build();
    }
}

Now REst Jersey Client:

public static void main(String[] args) {

        try {

            Student student = new Student();
            student.setName("JON");
            student.setAddress("Paris");
            student.setId(5);

            String resturl = "http://localhost:8080/RestJerseyClientXML/rest/StudentService/update";
            Client client = Client.create();
            WebResource webResource = client.resource(resturl);

            ClientResponse response = webResource.accept("application/xml")
                    .post(ClientResponse.class, student);
            String output = response.getEntity(String.class);

            System.out.println("Server response : " + response.getStatus());
            System.out.println();
            System.out.println(output);

            if (response.getStatus() != 200) {
                throw new RuntimeException("Failed : HTTP error code : "
                        + response.getStatus());
            }

        } catch (Exception e) {

        }
    }

Need Your Help

How to get access token after user is signed in from Gmail in Android?

android google-play-services google-signin android-googleapiclient

I am following Google Sign in for Android. Now I can get the idToken but my back end server that I have used earlier is expecting access Token as I was using Google+ Login earlier. Now I don't want...

Push a new ViewController and Pop the last one from NavigationStack

ios cocoa-touch uinavigationcontroller

Hey Guys i want to push a new controller onto the navigation stack and then remove the controller where i pushed from.