Ninja
Ninja

Reputation: 211

How to post form data using Jesrey?

Am new to jersey.Am trying to post two form data using jersey call.The following is my code,

public class Test {     

    private static String baseuri = "http://json/authenticate";


    /**
     * @param args
     */
    public static void main(String[] args) {        


        try {
            Client client = Client.create();    
            WebResource webResource = client.resource(baseuri);             

            MultivaluedMap<String, String> postBody = new MultivaluedMapImpl();
            postBody.add("X-Username", "admin");
            postBody.add("X-Password", "password");

            ClientResponse response =  webResource.type(MediaType.APPLICATION_FORM_URLENCODED_TYPE)
                            .post(ClientResponse.class, postBody);   


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

            // display response
            String output = response.getEntity(String.class);
            System.out.println("Output from Server .... ");
            System.out.println(output + "\n");
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}

While am trying to run this code , i get the following error

java.lang.RuntimeException: Failed : HTTP error code : 415.

Please any one help me with this..Thanks.

Upvotes: 2

Views: 1234

Answers (1)

Paul Samsotha
Paul Samsotha

Reputation: 209012

Using url encoded form type, we need to format the body in specific way. As state here

The control names/values are listed in the order they appear in the document. The name is separated from the value by = and name/value pairs are separated from each other by &.

So basically, the data should be sent in the form key1=value2&key2=value2, and any special characters should be url encoded. In your case, there are no special characters so we don't need any encoding, just formatting. So you client request might look something more like

WebResource resource = client.resource(Main.BASE_URI).path("form");

String username = "user";
String password = "pass";
StringBuilder builder = new StringBuilder();
builder.append("X-Username").append("=").append(username).append("&");
builder.append("X-Password").append("=").append(password);

ClientResponse response = resource
        .type(MediaType.APPLICATION_FORM_URLENCODED_TYPE)
        .post(ClientResponse.class, builder.toString());

String msg = response.getEntity(String.class);
System.out.println(msg);

response.close();

On the server side, you need to make sure the resource accepts (@Consumes) MediaType.APPLICATION_FORM_URLENCODED type data also, and has @FormParam annotations to extract the values (we can also us a MultivalueMap, but for easier access, we can use the annotation`. So your resource class might look something like

@Path("/form")
public class FormResource {

    @POST
    @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
    public Response doForm(@FormParam("X-Username") String username,
                           @FormParam("X-Password") String password) {
        return Response.ok("Good job " + username + "!").build();
    }
}

This should work fine, given all your other infrastructure parts are working.

Note: If you do have any special characters you need to encode, you can simple make use of java.net.URLEncoder and use encode(String part, String encType)

Upvotes: 1

Related Questions