Developers, Developers, Developers! Maksim Sorokin IT Blog

2Aug/11Off

Maven + Apache Felix + CXF: RESTful Webservice with CXF. Using POST.

It is another post in Maven + Apache Felix + CXF + DOSGi Series.

In this post I showed you how to create a RESTful webservice consuming and creating a String. However, the example was using @GET method. Here I will show, what changes need to be done in order to consume input from @POST. As usual, sources are available in the end of the post.

Simply change @GET to @POST and remove @PathParam("name") from MyService webservice interface:

package test.bundle;

import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

@Path("myService")
public interface MyService {

  @POST
  @Path("sayHello")
  @Produces(MediaType.TEXT_PLAIN)
  String sayHello(String name);
}

Then you can make POST requests to http://localhost:8080/myService/sayHello with request body. I suggest using Fiddler2 tool for debugging.

If you want to consume object (well, XML and then convert it into object), you will need to create message body reader and reference it in the Activator. An example of message body reader could be:

package dk.codeunited.ecosystem.integration.myRecord.pub.api;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;

import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.ext.MessageBodyReader;
import javax.ws.rs.ext.Provider;

import dk.codeunited.ecosystem.integration.myRecord.pub.api.pojos.Logbook;

@Provider
public class MyMessageReaderProvider implements MessageBodyReader<MyMessage> {

  @Override
  public boolean isReadable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mt) {
    return true;
  }

  @Override
  public MyMessage readFrom(Class<MyMessage> clazz, Type t, Annotation[] a, MediaType mt,
      MultivaluedMap<String, String> headers, InputStream is) {
    // reader an object from InputStream
  }
}

And then registration in Activator:

    restProps.put("org.apache.cxf.rs.provider", MyMessageReaderProvider.class.getName());

Here are source to POST example

Comments (0) Trackbacks (0)

Sorry, the comment form is closed at this time.

Trackbacks are disabled.