JAX-RS RESTEasy 3 Form to Post application/x-www-form-urlencoded Content Type

By Arvind Rai, March 10, 2015
In this page, we will create a client code using RESTEasy client framework. We will create a form using JAX-RS Form class and data will be posted to web service. The form content type will be application/x-www-form-urlencoded

javax.ws.rs.core.Form

JAX-RS provides javax.ws.rs.core.Form class that represents HTML form with application/x-www-form-urlencoded content type. JAX-RS Form class has param() method using which we add form elements.
Form param(String name, String value) 

Gradle File To Resolve JAR dependency for RESTEasy Client Framework

Find the gradle file To resolve JAR dependency for RESTEasy Client Framework.
build.gradle
apply plugin: 'java'
apply plugin: 'eclipse'
archivesBaseName = 'resteasyclient'
apply plugin: 'war'
version = '1' 
repositories {
    mavenCentral()
}
dependencies {
	compile 'org.jboss.resteasy:resteasy-jaxrs:3.0.10.Final'
	compile 'org.jboss.resteasy:resteasy-jackson2-provider:3.0.10.Final'
	compile 'org.jboss.resteasy:resteasy-client:3.0.10.Final'
}  

Client Code

In this example, we are creating a JAX-RS form and adding some form elements and using POST method we are sending data to a web service which will return JSON data.
RESTEasyClient.java
package com.concretepage;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Form;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.jboss.resteasy.client.jaxrs.ResteasyClient;
import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;
public class RESTEasyClient {
     public static void main(String[] args) {
	ResteasyClient client = new ResteasyClientBuilder().build();
        ResteasyWebTarget target = client.target("http://localhost:8080/resteasyservice-1/employee/manage/saveform");
        Form form = new Form();
        form.param("id", "333").param("name", "Ram").param("company", "ABCD");
        Entity<Form> entity = Entity.form(form);
        Response response = target.request(MediaType.APPLICATION_JSON).post(entity);
        String value = response.readEntity(String.class);
        System.out.println(value);
        response.close();  
    }
} 

Download Complete Source Code

POSTED BY
ARVIND RAI
ARVIND RAI







©2024 concretepage.com | Privacy Policy | Contact Us