Search code examples
javahttprestletmedia-type

Unsupported Media Type (415) for POST request to Restlet service


I POST to an endpoint like following:

import java.util.logging.Level;

import org.json.JSONException;
import org.json.JSONObject;
import org.restlet.ext.json.JsonRepresentation;
import org.restlet.representation.Representation;
import org.restlet.resource.Post;
import org.restlet.resource.ServerResource; 



           try {
                JSONObject jsonToCallback = AcceptorManager.getJsonFromClient();
                String test = jsonToCallback.getString("test");
                String st2 = jsonToCallback.getString("st2");
                ClientResource clientResource = new ClientResource(callback);
                clientResource.setMethod(Method.POST);
                Form form = new Form ();
                form.add("key1", val1);
                form.add("key2", "stat");
                Representation representation = clientResource.post(form, MediaType.APPLICATION_JSON);
           } catch (Exception e) {
                //Here I get "Unsupported Media Type (415) - Unsupported Media Type"
           }

And this is the endpoint:

public class test extends ServerResource{
    @Post
    public JSONObject testPost(JSONObject autoStackRep) throws JSONException, AcceptorException {
        JSONObject json=new JSONObject();
        try {
            json.put("result",false);
            json.put("id",1);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return json;
    }
}

How can I fix this issue?


Solution

  • Passing JSONObject as input parameter of your POST method doesn't make it accept appication/json. Restlet has several ways of specifying accepted Media-Type. You can specify it in @Post annotation like this:

    @Post("json")
    public Representation testPost(Representation autoStackRep)
    

    If only one extension is provided, the extension applies to both request and response entities. If two extensions are provided, separated by a colon, then the first one is for the request entity and the second one for the response entity. Note that parameter type is now Representation. You can use Representation.getText() method to retrieve content of response entity. You may also specify POJO as parameter type:

    @Post("json")
    public MyOutputBean accept(MyInputBean input)
    

    In this case you need Jackson extension to be able to map JSON to POJO and vice versa. Just make sure org.restlet.ext.jackson.jar is in your classpath. You may omit media type declaration when using POJO as parameter, in this case Restlet will try to apply all available converters to input stream to map it to your POJO.