blogger templates blogger widgets
This is part of a list of blog posts.
To browse the contents go to

JAX-RS: Sending form data


Form data could be easily consumed using @FormParam annotations.

Server code,
@Path("/hello")
public class HelloResource {
    @POST
    @Produces("text/plain")
    @Consumes("application/x-www-form-urlencoded") 
    public Response helloPost(@FormParam("username") String username ) {
        return Response.status(200).entity("[POST] Hello "+username+" from JAX-RS on WebSphere Application server").build();
    }
}

Client code,
//did not work, got runtime exception: java.lang.NoClassDefFoundError:org.apache.wink.common.internal.MultivaluedMapImpl
//neither was the class, javax.ws.rs.core.MultivaluedMapImpl available even at compile time.
String lsUrl = "http://localhost:9080/RSServer/HelloApp/hello";
RestClient client = new RestClient();
Resource resource = client.resource(lsUrl);
MultivaluedMap<String, String> queryParams = new MultivaluedMapImpl<String, String>();
queryParams.add("username", "John");
ClientResponse result = resource.contentType(MediaType.TEXT_PLAIN).queryParams(queryParams).post(new String("John"));
System.out.println(result.getEntity(String.class));

But invoking it using a form worked,
<!DOCTYPE HTML>
<%@page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Form Page</title>
</head>
<body>
 <h1>
Submit the following form</h1>
<form action="/RSServer/HelloApp/hello" method="post">
User Name: <input type="text" name="username" /> 
  <input type="submit" value="Submit" />
 </form>
</body>
</html>


No comments:

Post a Comment